본문 바로가기
TIL

[TypeScript] keyof typeof

by yo.na 2022. 9. 22.

✔ 목표 

const beer = ['TERRA','CASS'] as const;
const COLOR_CODE: TBeer = {
    TERRA: 'green',
    CASS: 'blue'
}

 

COLOR_CODE 의 타입을 beer 의 값('TERRA', 'CASS') 으로 제한하기 

 

✔ typeof

type TItem = typeof beer // type TItem = readonly ["TERRA", "CASS"]

type TItem = typeof beer[number] // type TItem = "TERRA" | "CASS"

 

✔ Mapped Type

const beer = ['TERRA','CASS'] as const;
type TBeer = { [key in typeof beer[number]]: string } 
/** type TBeer = {
    TERRA: string;
    CASS: string;
} */

const COLOR_CODE: TBeer = {
    TERRA: 'green',
    CASS: 'blue'
}

 

✔ 참고

https://itchallenger.tistory.com/170

 

타입스크립트 Mapped Type, KeyOf, TypeOf 정리

해당 글의 조회수가 꽤 나와서 내용을 보강하였습니다. 참고로 끼워넣은 게시물들도 읽어주세요... 0. typeof 연산자 해당 연산자는 자바스크립트에도 존재하지만 타입스크립트 타입, 인터페이스

itchallenger.tistory.com

https://stackoverflow.com/questions/55377365/what-does-keyof-typeof-mean-in-typescript

 

What does "keyof typeof" mean in TypeScript?

Explain to me what keyof typeof means in TypeScript Example: enum ColorsEnum { white = '#ffffff', black = '#000000', } type Colors = keyof typeof ColorsEnum; The last row is equivalent to...

stackoverflow.com