TS ValueOf<T> 구현방법

김민수·2023년 8월 22일
0
const UseAsConst = {
	준비 : 1,
	진행중 : 2,
	done : 3,
	cancel : 8,
    etc: 0,
} as const

const enum UseEnum {
	준비 = 1,
	진행중 = 2,
	done = 3,
	cancel = 8,
    etc= 0,
} 

//keyof typeof만 사용한 방식
type UseAsConstValueOf = (typeof UseAsConst)[keyof typeof UseAsConst]

type UseEnumValueOf = (typeof UseEnum)[keyof typeof UseEnum]

//제네릭 방식
type valueOf<T> = T[keyof T];

type User = {
    id: number,
    name: string,
    state: UseAsConstValueOf //valueOf<typeof UseEnum> | UseEnumValueOf
}

const kim: User = {id:1,name:"minsu", state:1};
console.log(kim);

ts에서 enum은 tsc에서 js로 변환시 즉시실행함수로 (preserveConstEnums 옵션을 줌으로 즉시실행함수로 번들링 안되게 할 수 있음) 번들링되고 다른 블로그에 많은 글처럼 Tree-shaking이 되지 않는다.
as const쓰면 속성이 readonly로 되어 삽입수정이 불가하고 각 속성의 타입을 리터럴 타입으로 추론한다.
암튼 enum관련된 글은 블로그에 많으니 다른 블로그에 글도 많고, 찾아보는걸 추천한다.

본론으로 돌아와서 Typescript에서 keyof는 있는데 valueOf는 없어서 제네릭을 이용한 방법과 typeOf와 keyOf를 구현 방법을 정리했다

0개의 댓글

관련 채용 정보