#Simplify type transformation

8 messages · Page 1 of 1 (latest)

umbral saddle
#

I want to run type transform like this:

type Source = [['foo', string], ['bar', number], ['baz', boolean]]
type Result = {
  foo: string,
  bar: number,
  baz: boolean
}

I've came up with a working solution, but I feel like it's a bit overcomplicated, and there should be a better way to do this. Am I right, or my solution is good enough?

Besides, my solution gives Record<'foo', string> & Record<'bar', number> & Record<'baz', boolean> instead of Result type, maybe that is another room for improvement

timber shadowBOT
#
eranikid#6947

Preview:```ts
// [T, U] -> Record<T, U>
type TupleToRecord<T> = T extends [infer R, infer S]
? R extends string
? Record<R, S>
: never
: never;

// [[R, S], [T, U]] -> [Record<R, S>, Record<T, U>]
type TuplesToRecords<T extends any[]> = {
[Index in keyof T]: TupleToRecord<T[Index]>;
...```

hoary orchid
#

i'm not sure how much better this is, but:

timber shadowBOT
#
mkantor#7432

Preview:```ts
// T | U -> T & U
type UnionToIntersection<U> = (
U extends any ? (k: U) => void : never
) extends (k: infer I) => void
? I
: never

type Transform<
T extends readonly (readonly [
PropertyKey,
unknown
])[]

= UnionToIntersection<
{[K in keyof T]: Record<T[K][0], T[K][1]>}[number]

type Flatten<T> = {
[K in keyof T]: T[K]
}

type Source = [
["foo", string],
["bar", number],
["baz", boolean]
]
type Result = Flatten<Transform<Source>>
// ^?```

hoary orchid
#

i wanted something like this to work, but sadly it does not:

timber shadowBOT
#
type Transform<T extends readonly (readonly [PropertyKey, unknown])[]> = {
  [K in keyof T as T[K][0]]: T[K][1]
//                 ^^^^^^^
// Type 'T[K][0]' is not assignable to type 'string | number | symbol'.
//   Type 'T[keyof T][0]' is not assignable to type 'string | number | symbol'.
//     Type 'T[string][0] | T[number][0] | T[symbol][0]' is not assignable to type 'string | number | symbol'.
//       Type 'T[string][0]' is not assignable to type 'string | number | symbol'.
// Type '0' cannot be used to index type 'T[K]'.
}
hoary orchid
#

(that particular error can avoided, but everything i tried resulted in the value types getting unioned together)

umbral saddle
#

Definitely better, I was hoping some direct mapping from tuple of pairs to object would be possible, but apparently mapping inside the tuple, and then to intersection is the way to go, thanks!