πŸ’™ Typescript/type-challenges

[TS] type-challenges : 11. Tuple to Object

선달 2023. 7. 3. 15:22
λ°˜μ‘ν˜•

문제

λ°°μ—΄(νŠœν”Œ)을 λ°›μ•„, 각 μ›μ†Œμ˜ 값을 key/value둜 κ°–λŠ” 였브젝트 νƒ€μž…μ„ λ°˜ν™˜ν•˜λŠ” νƒ€μž…μ„ κ΅¬ν˜„ν•˜μ„Έμš”.

 

μ˜ˆμ‹œ

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'}

 

풀이

객체의 킀도, 값도 Tλ°°μ—΄μ˜ μš”μ†ŒκΈ° λ•Œλ¬Έμ— ν‚€κ°’ kvκ°€ T[number]에 μ†ν•΄μžˆκ³  이 것이 킀인 λ™μ‹œμ— 값이라고 λͺ…μ‹œν•΄μ£Όλ©΄ ν•΄κ²°λœλ‹€.

μ΄λ•Œ TλŠ” string λ˜λŠ” number κ°€ ν¬ν•¨λœ λ°°μ—΄μ΄λΌλŠ” 점도 λͺ…μ‹œν•΄μ€€λ‹€.

type TupleToObject<T extends readonly (string|number)[]> = {
  [kv in T[number]] : kv; 
}

 

좜처

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

 

λ°˜μ‘ν˜•

'πŸ’™ Typescript > type-challenges' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

[TS] type-challenges: 18. Length of Tuple  (0) 2023.07.05
[TS] type-challenges: 14. First of Array  (0) 2023.07.04
[TS] type-challenges : 7. Readonly  (0) 2023.06.28
[TS] type-challenges : 4. Pick  (0) 2023.06.28
[TS] type-challenges : 13. Hello World  (0) 2023.06.28