[TypeScript] Array에서 Union Type 추출하기

Slowly But Surely·2024년 1월 31일
// Step 1: Const assertion 
const tableColumns = ["name", "address", "nationality", "gender", "birth_date"] as const;

// Step 2: Const array에서 Union type 추출
type TableColumn = (typeof tableColumns)[number];

// Step 3: Mapped type으로 type 정의
type TableDataColumns {
  [K in TableColumn]: string;
}

(typeof tableColumns)[number]는 const array tableColumns의 값들을 이용해 union type을 만든다. typeof threadInfoKeys 는 readonly 타입의 ["tid", "name", "kernel_use", "user_use", "mem"]인데, [number]을 붙여 이 타입에서 인덱싱을 할 수 있고 결과적으로 "tid" | "name" | "kernel_use" | "user_use" | "mem" 타입을 추출할 수 있다.

profile
안녕하세요

0개의 댓글