Tech.log/프론트엔드
[Interfaces vs Type Aliases]
SpaciousKitchen
2021. 4. 10. 01:31
Type Aliases 비교적 Interfaces 처럼 작용한다. 이 둘은 무슨 차이가 있을까 ?
Interfaces는 여러곳에서 새로운 이름(new name)을 만든다. 반면 Type Aliases 유일(unique)하다.
두 코드를 비교해 보자
//interface 예시
interface Window {
title: string
}
interface Window {
ts: import("typescript")
}
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
해당 코드를 사용하면, 기존에 존재하는 Window interface에 'ts' 라는 새로운 field를 추가하게 된다.
그러나
//type예시
type Window = {
title: string
}
type Window = {
ts: import("typescript")
}
// Error: Duplicate identifier 'Window'.
type Window에 경우는 에러는 내뿜는다.
따라서, Interfaces는 확장 가능 type Aliases는 extend되거나 implement될 수 없다.
그럼 언제 Type Aliases 를 써야하는가 ?
interface로 표현할 수 없는 형태(shape)이고 union, tuple 일때 사용한다.
//예시 Union-Type
type Race = 'string | number'; // string과 number를 동시에 타입으로 지정해줍니다.
const win: Rating = 1;
function racePrint(rating: Race) {
console.log(rating);
};
racePrint(1); // 1
racePrint(승리); // '승리'