이것저것 코딩공부/기타

[Typescript] interface, type

김쨔뿌 2022. 5. 16. 11:01

Type

- 여러 형식의 타입을 지정해 줄 수 있다.

// 타입 1개만 지정
type A = string;

// 타입 여러개 지정
type B = string | number;

// 객체형식
type C = {
    x:number;
    y:string;
}

// 사용
const alphabet = (a:A, b:B, c:C) => {
    console.log(a, b, c)
}

 

Interface

- 객체 형태의 타입을 지정해준다. 

interface Hello {
    good:string;
    bad:string;
}

const hi = (hello:Hello) => {
    console.log(hello.good);
    console.log(hello.bad);
}

hi({good:"good to see you", bad:"wtf"});

 

interface가 가지는 기능의 대부분은 type이 사용할 수 있다. 다만 확장의 경우, type은 생성한 뒤 변화할 수 없지만 인터페이스는 생성 후에 변경할 수 있다.

 

interface Hello {
    good:string
}

interface Hello {
    bad:number
}

// 이 시점에서 Hello라는 인터페이스는 good와 bad에 대한 타입을 모두 가지고 있다.
type Hello = {
    good: string
}

// type은 이 시점 이후로 변경할 수 없다.

 

대신 둘 모두 새로운 명칭의 interface와 type을 생성하여 다른 interface나 type을 가져오는 방식 = 확장을 할 수 있다.

 

interface의 확장

interface Fruit {
    name : string
}

interface Apple extends Fruit{
    apple : number
}

// Apple은 name, apple 의 타입을 가지게 된다.

 

type의 확장

type Fruit = {
    name: string
}

type Apple = Fruit & {
    apple : number
}

// Apple은 name, apple 의 타입을 가지게 된다.

 

공식문서에서는 우선 interface를 사용하고 문제가 있을 시 type을 사용하기를 바란다고 적혀있다. 

객체타입으로 표현이 가능하다면 interface를 사용하고 그 외에는 type을 쓰는게 좋을듯?