타입스크립트 6 (인터페이스)

hojoon·2023년 3월 21일
0

타입스크립트

목록 보기
6/9

what art interfaces?

타입을 만들어내는 방식..?

차근 차근 알아보자

function helloInter(person: { name: string; age: number }): void {
  console.log(`안녕하세요! ${person.name}입니다. `);
}

const p1: { name: string; age: number } = {
  name: "mark",
  age: 39,
};

helloInter(p1);
interface person1 {
  name: string;
  age: number;
}

function helloInter(person: person1): void {
  console.log(`안녕하세요! ${person.name}입니다. `);
}

const p1: person1 = {
  name: "mark",
  age: 39,
};

helloInter(p1);

이렇게 사용할 수 있다.

처음으로 interface를 만든것이다.!!

자바스크립트에 없는 인터페이스 문법이 컴파일했을때 자바스크립트에서는 어떻게 나올까?

"use strict";
function helloInter(person) {
    console.log(`안녕하세요! ${person.name}입니다. `);
}
const p1 = {
    name: "mark",
    age: 39,
};
helloInter(p1);

엥? 없다. 아무리봐도 interface는 안보인다.
파일 타임에만 interface를 이용해서 에러를 체크한다.

optional property

  • 상황에 따라서 있어도 되고 없어도 되는 property
interface Person2 {
  name: string;
  age?: number;
}

물음표를 붙여주면 된다.

이렇게 있을수도 있고 없을 수도 있고!!

optional property(indexable type)

interface Person3 {
  name: string;
  age?: number;
  [index: string]: any;
}

// a['index'] -> ["whatever"] -> ["ㅇㅁㄴㅇㅁㄴㅇㅁㄴㅇㄴㅁ"]
function hello4(person: Person3): void {
  console.log(`안녕하세요 ${person.name} 입니다.`);
}

const p31: Person3 = {
  name: "mark",
  age: 29,
};

const p32: Person3 = {
  name: "anna",
  systers: ["sung", "chan"],
};

const p33: Person3 = {
  name: "Bokda",
  father: p31,
  mother: p32,
};

interface 안의 function을 정의하는법

interface Person4 {
  name: string;
  age: number;
  hello(): void;
}

const p41: Person4 = {
  name: "mark",
  age: 39,
  hello: function (): void {
    console.log(`안녕하세요 ${this.name}`);
  },
};

const p42: Person4 = {
  name: "mark",
  age: 39,
  hello(): void {
    console.log(`안녕하세요 ${this.name}`);
  },
};

const p43: Person4 = {
  name: "mark",
  age: 39,
  hello: (): void => {},
  // 화살표함수는 this 못쓴다.
};

실행결과!

interface를 이용해서 클래스를 만들어내는 방법

personIC.hello();

이렇게 할 수 있다.

interface extends interface


interface 상속은 이런식으로도 쓰인다.

interface 상속은 나중에 대규모 프로젝트를 진행할 때 유용하게 쓰일 수 있을것 같다.

function interface

함수에 대해서 인터페이스를 만들어내는 방법

이렇게 사용한다.

이렇게 사용하면 에러임!

하지만 이건 된다??
helloPerson1 은 인터페이스 helloPerson과의 관계가 중요하기 때문!

그래서 이건 당연히 안된다.
왜냐면 number는 옵셔널한 프로퍼티인데 함수에서 age를 당연히 있어야 한다고 말해버리기 때문에 에러를 발생시킨다.

Readonly interface properties

업로드중..

  • readonly는 한번 만들어지고 바뀌지 않는 타입
  • 우리가 타입스크립트를 사용하는 의도는 컴파일단계에서 에러를 잡고 우리의 의도를 담아서 사용의도를 다른 사람들에게 알려주는 것인데 이러한 측면에서 readonly 는 유용하게 쓰일 수 있다.

type alias vs interface

타입 별칭과 인터페이스는 뭐가 다를까?

function

//alias
type EatType = (food: string) => void;

//interface
interface IEat {
  (food: string): void;
}

Array

//alias
type personList = string[];

//interface
interface IPersonList {
  [index: number]: string;
}

intersection

// intersection
interface ErrorHandling {
  succes: boolean;
  error: { message: string };
}

interface ArtistData {
  artists: { name: string }[];
}

type ArtistResponseType = ArtistData & ErrorHandling;

interface IArtistResponse extends ArtistData, ErrorHandling {}

let art: ArtistResponseType;
let iar: IArtistResponse;

union

interface Bird {
  fly(): void;
  layEggs(): void;
}
interface Fish {
  swim(): void;
  layEggs(): void;
}

type PetType = Bird | Fish;

interface Ipet extends PetType {} //유니온 타입은 인터페이스한테 상속할 수 없음.

class pet implements PetType {} //클래스한테 넣어줄 수 없음.

declaration merging

알리아스는 할 수 없는 행위!!!

interface merging {
  a:string
}
interface merging {
  b:string
}
// 이름이 같은 인터페이스를 사용하면 나중에 사용할 때 알아서 합쳐짐 
// 알리아스는 이름이 겹친다고 에러가 발생함!
let mi:merging;

mi.을 하면 a와 b 를 둘 다 쓸 수 있다.

결과적으로 알리아스는 어떤 타입을 부르는 이름을 만들어내는 것이고 인터페이스는 어떤 타입자체를 만들어낸다고 볼 수 있다.

profile
프론트? 백? 초보 개발자의 기록 공간

0개의 댓글