타입스크립트에서 객체 타입을 지정하는 방식으로 거의 비슷한 기능을 가진다.
type B = {
a: string;
b: number;
};
interface C {
a: string;
b: number;
}
type alias
type TA = {
a: string;
};
type TB = {
b: string;
};
type TC = TA & TB & { k: string };
interface
interface IA {
a: string;
}
interface IB {
b: string;
}
interface IC extends IA, IB {
k: string;
}
개인적으로는 인터페이스가 여러 개 등록 가능한 점 빼고 문법이 java 상속과 똑같이 사용할 수 있어 직관적인 것 같다.
선언적 확장
type은 새로운 속성을 추가하기 위해 같은이름으로 또 선언할 수 없고 interface는 가능하다.
따라서 interface를 사용할 때 globa.d.ts 등 기본적으로 사용되는 전역타입이랑 겹칠 수 있는 경우가 있으니 조심해야 한다.
type은 원시타입을 포함한 어디에든 사용할 수 있다.
type TString = string;
type TTuple = [string, number];
type TUnionStr = 'hell' | 'world';
type TUnionUnion = number | boolean;
An interface can only extend an identifier/qualified-name with optional type arguments.(2499)
인터페이스에는 객체만 사용 가능하다.
export type HelloType = 'hell' | 'world';
type HellosType = {
[key in HelloType]: string;
};
const hellos: HellosType = { hell: '1', world: '2' };
interface HellosInterface {
// A mapped type may not declare properties or methods.(7061)
[key in HellosType]: string;
}
interface는 computed property name을 사용할 수 없다.
For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type.
공식문서에 의하면 모르겠으면 일단 interface를 사용하라고 권장한다.
전역으로 사용하는 공공재 interface 의 중복 선언으로 타입이 합쳐지는 경우가 없이 잘 사용한다면 interface 사용에 문제가 없지 않을까 생각한다.