프론트엔드 스터디/Typescript

[TypeScript] 기초 - 타입 앨리어스(Type Alias)

옹재 2021. 7. 21. 16:13
728x90
반응형

타입 앨리어스(Type Alias)

타입 앨리어스는 새로운 타입을 정의합니다. 타입으로 사용할 수 있다는 점에서 인터페이스와 유사합니다.

interface Person {
  name: string,
  age?: number
}

// 빈 객체를 Person 타입으로 지정
const person = {} as Person;
person.name = 'Lee';
person.age = 20;
person.address = 'Seoul'; // Error

// 타입 앨리어스
type Person = {
  name: string,
  age?: number
}

// 빈 객체를 Person 타입으로 지정
const person = {} as Person;
person.name = 'Lee';
person.age = 20;
person.address = 'Seoul'; // Error

하지만 타입 앨리어스는 원시값, 유니온 타입, 튜플 등도 타입으로 지정할 수 있습니다.

// 문자열 리터럴로 타입 지정
type Str = 'Lee';

// 유니온 타입으로 타입 지정
type Union = string | null;

// 문자열 유니온 타입으로 타입 지정
type Name = 'Lee' | 'Kim';

// 숫자 리터럴 유니온 타입으로 타입 지정
type Num = 1 | 2 | 3 | 4 | 5;

// 객체 리터럴 유니온 타입으로 타입 지정
type Obj = {a: 1} | {b: 2};

// 함수 유니온 타입으로 타입 지정
type Func = (() => string) | (() => void);

// 인터페이스 유니온 타입으로 타입 지정
type Shape = Square | Rectangle | Circle;

// 튜플로 타입 지정
type Tuple = [string, boolean];
const t: Tuple = ['', '']; // Error

Type vs Interface

인터페이스는 extends 또는 implements 될 수 있지만 타입 앨리어스는 그럴 수 없습니다. 즉, 상속을 통해 확장이 필요하다면 인터페이스가 유리합니다.
하지만 인터페이스로 표현할 수 없거나 유니온 또는 튜플을 사용해야한다면 타입 앨리어스를 사용하는 편이 유리합니다.

interface PeopleInterface {
  name: string
  age: number
}

interface StudentInterface extends PeopleInterface {
  school: string
}

type PeopleType = {
  name: string
  age: number
}

type StudentType = PeopleType & {
  school: string
}

또한 인터페이스에서 할 수 있는 대부분의 기능들은 타입 앨리에스에서 가능하지만, 타입은 새로운 속성을 추가하기 위해서 다시 같은 이름으로 선언할 수 없지만 인터페이스는 항상 선언적 확장이 가능합니다.

interface Window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}

// 같은 interface 명으로 Window를 다시 만든다면, 자동으로 확장이 된다.

const src = 'const a = "Hello World"'
window.ts.transpileModule(src, {})

type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}

// Error: Duplicate identifier 'Window'.
// 타입은 안된다.

 

728x90
반응형