조건 | Type Alias | Interface |
---|---|---|
함수 사용이 가능한가? | ⭕ | ⭕ |
생성자 사용이 가능한가? | ⭕ | ⭕ |
튜플 사용이 가능한가? | ⭕ | ❌ 직접 구현 |
정의된 후 동일한 이름으로 확장 가능한가? | ❌ | ⭕ |
객체가 아닌 값을 사용할 수 있는가? | ⭕ | ❌ |
Computed Value를 사용할 수 있는가? | ⭕ | ❌ |
mapped type을 사용할 수 있는가? | ⭕ | ❌ |
union, intersection 키워드를 사용할 수 있는가? | ⭕ | ❌ |
미리보기를 자세히 보여줄 수 있는가? | ⭕ | ❌ |
⚠️: 특정 케이스에서만 가능함
👾 Type Alias
type Book = {
title: string;
};
type MyBook = Book & {
author: string;
};
const Frankenstein: MyBook = {
title: "Frankenstein",
author: "Mary Shelley",
};
&
을 사용해 intersection 의 형태로 타입 간 연결 및 확장👾 Interface
interface Book {
title: string;
}
interface MyBook extends Book {
author: string;
}
const Frankenstein: MyBook = {
title: "Frankenstein",
author: "Mary Shelley",
};
extends
를 사용해 타입 간 연결 및 확장👾 Type Alias
👾 Interface
* Computed Value: 프로퍼티 이름이 동적으로 계산되는 경우
👾 Type Alias
👾 Interface
Type Alias
👾 Interface
간단하게 사용하기에는 Type Alias도 나쁘지 않아보인다.
실제로 Interface에서 사용하려면 Type Alias보다 번거워지는 기능들도 있다.
하지만 확장을 해줄 때 새로운 선언이 필요 없고,
정적 타입 검사를 진행한다는 점에서 TS를 쓰는 목적에 더 부합한 것 같아 주로 interface를 사용하게 될 것 같다.
(실제로 TypeScript 공식 문서에서도 Interface의 사용을 권장하고 있다고 한다!)
React+TypeScript Cheatsheets - types or interfaces
TS Documentation - Differences Between Type Aliases and Interfaces
[Typescript] Type Alias vs Interface