타입스크립트에서는 type과 interface가 많이 사용된다. 이 둘은 어떻게 보면 비슷해보일 수도 있는데 어 공통점을 가지고 있고 또 차이점은 무엇인지 알아보도록 하자.
type NewType = {
x: number;
y: number;
};
type NewType2 = "문자1" | "문자2"
interface NewInterface {
x: number;
y: number;
}
//computed value
type names = 'firstName' | 'lastName';
type NameTypes = {
[key in names]: string; // 사용o
}
interface NameInterface {
[key in names]: string; // 사용x
}
type은 객체뿐만 아니라 유니온(Union) 타입 및 인터섹션(intersection) 타입을 만드는 데 사용할 수 있고, computed value 사용이 가능하다.
interface는 오직 객체타입 정의만 가능하다.
interface NewInterface2 extends NewInterface1 {
b: string;
}
type NewType2 = NewType1 & {
b: string;
};
type과 interface는 모두 확장이 가능하다.
type은 & 연산자를 이용해 이미 지정한 타입을 확장할 수 있다.
interface는 extends 키워드를 이용해 이미 지정한 타입을 확장할 수 있다.
interface는 선언적 확장(자동 확장)이 가능하다. 선언적 확장이란 동일한 이름으로 interface를 또 선언해줬을 경우 자동적으로 하나의 타입으로 합쳐준다.
type은 선언적 확장이 되지 않아 동일한 타입을 재선언시 오류가 난다.
=> 확장에 있어서는 type보다 interface가 더 적합하다고 할 수 있다.