[TypeScript] - keyof, typeof 그리고 union

Hunter Joe·2025년 11월 30일

미리 Union타입을 만들어서 사용하는 방법과 자료구조에서 Union 타입을 추출해는 방법이 있다.

기본적인 Union 타입 선언

type Fruit = "apple" | "orange" | "lemon"| "melon"

const myFruit: Fruit  = "kiwi" // Type '"kiwi"' is not assignable to type 'Fruit'

const yourFruit: Fruit = "apple"

배열에서 Union 타입 추출하기

const fruits = ["apple", "orange", "lemon"] as const

type Fruits = typeof fruits[number]

객체에서 Union 타입 추출하기 (key, value)

const countryCurrency = {
	KOREA : "KRW",
  	USA : "USD",
  	CANADA : "CAD",
} as const;

type Country = keyof typeof countryCurrency
type Currency = (typeof countryCurrency)[keyof typeof countryCurrency]
profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글