상세 컨텐츠

본문 제목

type vs interface

Typescript

by 일단두잇 2023. 1. 26. 16:20

본문

반응형

Typescript에서 객체 타입을 만드는 방법 중에 

type과  interface가 있습니다.

 

사용방법이나 사용 이유가 거의 비슷한데요. 

많은 프로젝트에서 2가지 방법중에 고민하는 경우가 많이 있습니다.

 

간략하게 비교해보면 아래와 같습니다.


type과 interface의 유사한 기능

 

1. 선언

type BirdType = {
  wings: 2;
};

interface BirdInterface {
  wings: 2;
}

const bird1: BirdType = { wings: 2 };
const bird2: BirdInterface = { wings: 2 };

 

2. 확장

 - type은 & 사용

 - interface는 extends를 사용하여 확장

type Robin = { nocturnal: false } & BirdInterface;

interface Peacock extends BirdType {
  colourful: true;
  flies: false;
}

 


 

type과 interface의 차이점

 

1. 재정의

 - type : 재정의가 불가

 - interface : 재정의가 가능하여 속성을 추가 할 수 있음

interface BirdInterface {
  wings: number;
}
interface BirdInterface {
  title: string;
}

// 아래와 같습니다.
/*interface BirdInterface { 
  wings: number;
  title: string;
}*/
type BirdType {
  wings: number;
}
type BirdType {
  title: string;
}

// Error: Duplicate identifier 'BirdType'.

 

2. Error Message

- interface가 에러메시지가 간결합니다.

  type Owl = { wings: 2; nocturnal: true };
  interface Chicken {
    wings: 2;
    nocturnal: boolean;
    flies: boolean;
  }
  let owl: Owl = { wings: 2, nocturnal: true };
  let chicken: Chicken = { wings: 2, colourful: false, flies: false };

  owl = chicken;
  chicken = owl;

 

- type 에러 메시지 : type을 할당 할 수 없으며, 해당 프로퍼티가 없다

- interface 에러 메시지 : 해당 프로퍼티가 없다.

 


두 가지 방법 모두 작성방법이나 기능적으로 비슷하지만, 굳이 선택하자면 interface

 

기존 선언을 건드리지 않고 재정의 할 수 있으며 에러메시지가 간결한것도 큰 장점이 될수 있습니다.

실제 type으로 작성하다보면 꽤 긴 에러메시지를 마주치게 됩니다.

 

따라서, 프로젝트내에서 정한 표준을 따라가야 하지만 굳이 선택한다면 interface가 좀더 좋아보입니다.

 

※ 참고자료

https://www.typescriptlang.org/docs/handbook/2/objects.html

 

Documentation - Object Types

How TypeScript describes the shapes of JavaScript objects.

www.typescriptlang.org

 

반응형

관련글 더보기

댓글 영역