rimo030 / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
3 stars 0 forks source link

no - 4179 Flip #108

Open rimo030 opened 7 months ago

rimo030 commented 7 months ago
type Flip<T> = {
  [K in keyof T as T[K] extends string | number | boolean ? `${T[K]}` : never] : K
}
import type { Equal, Expect, NotEqual } from '@type-challenges/utils'

type cases = [
  Expect<Equal<{ a: 'pi' }, Flip<{ pi: 'a' }>>>,
  Expect<NotEqual<{ b: 'pi' }, Flip<{ pi: 'a' }>>>,
  Expect<Equal<{ 3.14: 'pi', true: 'bool' }, Flip<{ pi: 3.14, bool: true }>>>,
  Expect<Equal<{ val2: 'prop2', val: 'prop' }, Flip<{ prop: 'val', prop2: 'val2' }>>>,
]
rimo030 commented 7 months ago

Record<Key, Value> 유틸리티 타입을 이용해 T가 [key : string] : string | number | boolean임을 명시하는 방법도 있다.

type Flip<T extends Record<string, string | number | boolean>> = {
  [K in keyof T as `${T[K]}`] : K
}