Tuple To Object - easy - [Type Challenge]

강성훈·2023년 1월 23일
1

type-challenges

목록 보기
3/20

by sinoon @sinoon

배열(튜플)을 받아, 각 원소의 값을 key/value로 갖는 오브젝트 타입을 반환하는 타입을 구현

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const

type result = TupleToObject<typeof tuple>

만들 타입이 받는 타입 변수는 readonly인 array이다.

type TupleToObject<T extends readonly any[]>

그 후 모든 요소들을 새로운 객체 타입에 넣어준다.

type TupleToObject<T extends readonly any[]> = {[t in T[any]]: any}

위와 같이 key값이 잘 적용 된 것을 확인 할 수 있다.
마찬가지로 value에도 t값을 주게되면 원하던 결과를 얻을 수 있다.

type TupleToObject<T extends readonly any[]> = {[t in T[any]]: t}
```![](https://velog.velcdn.com/images/ksh5324/post/28138e39-8eaf-488f-93f1-b208d7ae8a2d/image.png)
profile
고등학생 주니어 개발자

0개의 댓글