요약
Type Alias는 모든 타입을 선언할 때 사용할 수 있고
Interface는 객체에 대한 타입을 선언할 때 사용될 수 있다.
차이점은 확장 가능 여부이며
확장 불가능한 타입 선언시 Type Alias를
확장 가능한 타입 선언시 Interface를 사용한다.
설명
사실 제일 최근 프로젝트를 하면서 type alias는 모든 타입을 선언할 때 사용할 수 있어서
거의 모든 객체 데이터 타입을 type alias로 설정해주었습니다.
//interface
interface Person {
name: string,
age?: number
}
const person = {} as Person;
person.name = 'Kim';
person.age = 25;
person.address = 'Seoul'; // Error
// type alias
type Person = {
name: string,
age?: number
}
const person = {} as Person;
person.name = 'Kim';
person.age = 25;
person.address = 'Seoul'; // Error
위 코드와 같이 interface와의 차이점을 크게 느끼지 못했기 때문입니다.
typescript 공식문서에 따르면 type alias와 interface의 가장 큰 차이점은
type alias 는 새 프로퍼티를 추가할 수 없고
interface 는 항상 확장 될 수 있다는 점입니다.
아래는 예시 코드 입니다.
interface 는 Person 이라는 같은 식별자를 사용해도 선언 병합이 가능하지만
type alias 는 에러를 발생 시킵니다.
공식문서에서는 type 사용이 필요하지 않는 이상 interface 사용을 더 권장하고 있습니다.
타입스크립트 핸드북에서도 확장이 용이해야한다는 프로그래밍 원칙에 따라 객체 타입 선언시 interface 사용을 권장하고있습니다.
Ref
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
타입 별칭 | 타입스크립트 핸드북
타입 별칭 (Type Aliases) 타입 별칭은 특정 타입이나 인터페이스를 참조할 수 있는 타입 변수를 의미합니다. 예를 들면 아래와 같습니다. 위와 같이 string, number와 같은 간단한 타입 뿐만 아니라 inter
joshua1988.github.io
https://tecoble.techcourse.co.kr/post/2022-11-07-typeAlias-interface/
interface vs type alias
what is the difference between interface and type alias? typescript…
tecoble.techcourse.co.kr
'TypeScript' 카테고리의 다른 글
[typescript] 나는 제네릭을 아는가? (2) | 2023.09.28 |
---|---|
[TypeScript] Enum, Interface, 타입별칭, 타입추론 (0) | 2023.05.31 |
[TypeScript] 프로젝트 환경설정과 문법 (0) | 2023.05.30 |