JavaScript › TypeScript

TypeScript 중급: Type Aliases, Type Guard

목차

Type Aliases

type StrOrNum = number | string;

타입 가드

typeof 연산자와 조건문을 사용해서, 숫자 타입 변수에 number | string 값을 넣을 때 생기는 오류를 방지한다.

if (typeof price === 'string') {
  itemPrice = 0;
} else {
  itemPrice = price;
}

이렇게 코드로 타입을 검증하는 것을 타입 가드라고 한다.

참고: TypeScript Handbook: Advanced Types