This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
59. implement MapStringUnionToObjectUnion<U>
Solution:
type MapStringUnionToObjectUnion<U extends string> = { [K in U]: { value: K; };}[U];
Explanation:
- We define a generic type
U
which extendsstring
. This ensures that the input to ourMapStringUnionToObjectUnion
type will be a string union (e.g.'1' | '2'
). - We use a mapped type to iterate over each string literal in the union type
U
. - For each string literal
K
inU
, we define an object literal with avalue
key whose value is the string literalK
. - We wrap this object literal in square brackets
[K in U]
to create an array of such object literals, indexed by the string literals inU
. - Finally, we index into this array with the generic type
U
to obtain a union of all the possible object types.