프로그래밍 언어/TypeScript 문제풀이

[type-challenges] 11_Tuple to Object

닉네임이 왜 필요해 2022. 5. 23. 00:29

 

Q: 

source : https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.md

 

GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge

Collection of TypeScript type challenges with online judge - GitHub - type-challenges/type-challenges: Collection of TypeScript type challenges with online judge

github.com

Give an array, transform into an object type and the key/value must in the given array.

For example

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

type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}

A : 

type TupleToObject<T extends readonly any[]>  = any

여기서 extends readonly any[ ] 를 알아보자 

다양하게 활용될 수 있는데 예제를 통해 알아보자

type FirstEntry<T extends readonly unknown[]> = T[0];

위처럼 T[0]을 이용하여 인덱싱이 가능하다. 

그렇다면 길이도 출력할 수 있지 않을까?

type Length<T extends readonly unknown[]> = T['length'];

'length' 로 사용한다는 점에서 조금 까다롭지만 기억해 둘만한 type 연산이다.

그렇다면 위문제는 어떻게 풀 수 있을까?

 

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

type test = TupleToObject<typeof tuple>

이 결과는 아래와 같다 

흠 값이 안들어갔다.

 

값을 넣어줘보자

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

type test = TupleToObject<typeof tuple>

흠.. 여기서 요소를 하나씩만 뽑으면 되는데..

 

아니지 ... 

key값을 바로 넣어주기만하면?

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

type test = TupleToObject<typeof tuple>

 

정답이다!!

 

여기서 number는 튜플을 순회할때 사용이 가능하다.