✔ 목표
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
'TIL' 카테고리의 다른 글
ChatGPT 사용 후기 (0) | 2023.02.18 |
---|---|
[Java] 문자열 포함 여부 확인 contains() / 문자열 비교 equals() 메서드/ == 연산자 차이 (0) | 2023.01.25 |
매개변수(Parameter) vs 인자(Argument) (0) | 2022.06.15 |
Session / JWT 차이점, 장단점 (0) | 2022.05.27 |
[Database] MySQL vs MongoDB 차이점 (0) | 2022.04.18 |