타입 별칭(type alias)이란?

타입 별칭(type alias)은 특정 타입이나 인터페이스 등을 참조할 수 있는 타입 변수를 의미합니다.

즉, 타입에 의미를 부여해서 별도의 이름으로 부르는 것입니다.

타입 별칭은 반복되는 타입 코드를 줄여 줄 수 있습니다.

타입 별칭 예시 코드

// 타입 별칭 정의
type name = string;
let jon: name = "jon"

// 타입 별칭 정의
// string | number 타입을 반복 사용을 줄일 수 있음
type MyMessage = string | number;
function logText(text: MyMessage)  {
 console.log(text);
}
let messageStr: MyMessasge = 'hello';
logText(messageStr);
let messageNum: MyMessage = 10;
logText(messageNum);

타입별칭과 인터페이스의 차이점

타입 별칭과 인터페이스 사용 구분

먼저, 인터페이스를 주로 사용해보고 타입 별칭이 필요할 때 타입 별칭을 쓰는 것이 권장됩니다.

타입 별칭의 사용

타입 별칭은 주로 원시 데이터 타입, 인터섹션 타입, 유니언 타입 등에 사용됩니다.

type name = string;
type text = string | number;
type Admin = Person & Developer;

타입 별칭은 아래와 같이 유틸리티 타입(utility type)과 맵드(mapped)타입과도 연동하여 사용할 수 있습니다.

//  유틸리티 타입 pick
type Profile = {name: string, age: number};
type name = Pick<Profile, 'name'>

 // 맵드 타입
type Picker<T, K extends keyof T> = {
  [P in K]: T[P];
}