lxxmnmn / type-challenges

TypeScript type challenges
https://tsch.js.org/
MIT License
0 stars 0 forks source link

11 - Tuple to Object #4

Open lxxmnmn opened 3 months ago

lxxmnmn commented 3 months ago

Tuple to Object easy #object-keys

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

/* _____________ Your Code Here _____________ */

type TupleToObject<T extends readonly PropertyKey[]> = {
  [key in T[number]]: key;
};
/* _____________ Test Cases _____________ */

import type { Equal, Expect } from '@type-challenges/utils'

const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
const tupleNumber = [1, 2, 3, 4] as const
const sym1 = Symbol(1)
const sym2 = Symbol(2)
const tupleSymbol = [sym1, sym2] as const
const tupleMix = [1, '2', 3, '4', sym1] as const

type cases = [
  Expect<Equal<TupleToObject<typeof tuple>, { 'tesla': 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y' }>>,
  Expect<Equal<TupleToObject<typeof tupleNumber>, { 1: 1, 2: 2, 3: 3, 4: 4 }>>,
  Expect<Equal<TupleToObject<typeof tupleSymbol>, { [sym1]: typeof sym1, [sym2]: typeof sym2 }>>,
  Expect<Equal<TupleToObject<typeof tupleMix>, { 1: 1, '2': '2', 3: 3, '4': '4', [sym1]: typeof sym1 }>>,
]

// @ts-expect-error
type error = TupleToObject<[[1, 2], {}]>
lxxmnmn commented 3 months ago

PropertyKey

string | number | symbol 유니온 타입을 가리키는 타입스크립트 전역 타입

// string | number | symbol
type randomKey = PropertyKey;

참고

propertykey-type