"Boldness has genius, power, and magic in it." - Johann Wolfgang von Goethe

TypeScript

[TS] TypeScript Type 별칭(Type Alias)

Toproot 2021. 9. 2. 15:44
728x90
728x90

image

📘 타입 별칭 (Type Alias)

  • Interface 랑 비슷해 보입니다.
  • Primitive, Union Type, Tuple, Function
  • 기타 직접 작성해야하는 타입을다른 이름을 지정할 수 있습니다.
  • 만들어지 타입의 refer(별명)로 사용하는 것이지 타입을 만드는 것은 아닙니다.

Aliasing Primitive

type MyStringType = string;

const str = 'world';

let myStr: MyStringType = 'hello'; // 같은 형식이기 때문에 같음
myStr = str;

Aliasing Union Type

let person: string | number = 0;
person = 'Mark';

type StringOrNumber = string | number;

let another: StringOrNumber = 0;
another = 'Anna';

// 1. 유니온 타입도 A도 가능하고 B도 가능한 타입
// 2. 길게 쓰는 걸 짧게

Aliasing Tuple

let person: [string, number] = ['Mark', 35];

type PersonTuple = [string, number];

let another: PersonTuple = ['Anna', 24];

// 1. 튜플 타입에 별칭을 줘서 여러군데서 사용할 수 있게 한다.

Aliasing Function

type EatType = (food: string) => void;


인터페이스와 Alias를 혼용해서 쓸 때 구분하는 법

  • 타입으로서의 목적이나 존재가치가 명확하면 인터페이스 사용
  • 다른대상을 가리킨다거나 별명으로서만 존재한다면 Alias 사용
  • 자신만의 기준을 잘 세우기!

728x90
728x90