타입스크립트에서 타입을 정의하는 방식은 두 가지가 있다. 바로 type alias
와 interface
의 사용이다.
type alias와 interface는 선언부터 사용까지 많은 공통점을 가진다.
1type Person = {2 name: string;3 age: number;4};5
6const jongmin: Person = {7 name: "이종민",8 age: 26,9};
1interface Person {2 name: string;3 age: number;4}5
6const jongmin: Person = {7 name: "이종민",8 age: 26,9};
두 방식을 비교해보면 선언 할 때 =
의 유무 외에는 다른 점이 없어보인다. 이처럼 type alias와 interface의 선언 방식은 유사하다.
implements
, extends
를 통한 상속에 있어서도 TypeScript 이전 버전에서는 type alias로 extends 할 수 없었지만, 2.7 버전부터 교차 타입(Intersection Types)을 생성함으로써 가능해졌다.
1type Animal = {2 name: string;3};4
5type Puppy = Animal & {6 culryHair: boolean;7};8
9// type alias는 & 키워드를 통해 상속한다
1interface Animal {2 name: string;3}4
5interface Puppy extends Animal {6 culryHair: boolean;7}8
9// interface는 extends 키워드를 통해 상속한다
타입 정의 내에서 union 연산자 (
|
)를 사용하는 경우에는extends
와implements
사용이 불가능 함을 주의한다.
그렇다면 type alias와 interface에는 어떤 차이점이 있을까?
선언 병합이란 같은 이름으로 선언된 두 개 이상의 개별적인 선언을 하나의 정의로 병합하는 것을 말한다.
1interface Puppy {2 name: string;3}4
5interface Puppy {6 breed: string;7}8
9interface Puppy {10 culryHair: boolean;11}12
13const molly: Puppy = {14 name: "Molly",15 breed: "poodle",16 culryHair: true,17};
위의 예시처럼 Puppy
라는 같은 이름으로 세 번의 선언이 이루어졌는데, 이후 molly
라는 변수를 선언 할 때는 Puppy
interface에 개별적으로 선언 된 프로퍼티가 포함되어 있음을 알 수 있다.
1type Puppy = {2 name: string;3};4
5type Puppy = {6 breed: string;7};8
9type Puppy = {10 culryHair: boolean;11};12
13// error TS2300: Duplicate identifier 'Puppy'
하지만 type alias 로는 선언 병합 대신 에러만 확인 할 수 있다.
이와 같이 interface 의 경우 같은 이름으로 여러 번 선언해도 컴파일 시 합쳐지기 때문에 확장성이 좋다는 특징을 가진다. 따라서 일반적으로 interface 를 사용하며 union (|
) 혹은 tuple ([]
)과 같이 type
이 꼭 필요한 경우에는 type alias 를 사용하는 것이 좋아보인다.
또한 외부에 public 으로 공개할 API로는 확장성을 위해 interface 를 사용하는 것이 권장된다.