const obj = [
{
key: 'fruit',
value: ['apple', 'banana']
},
{
key: 'meat',
value: ['pork', 'chicken']
}
] as const;
I want to generate type
type T = {
'fruit': 'apple' | 'banana',
'meat': 'pork' | 'chicken'
}
I searched but I can't find how to use value as a key. How can I generate type from the object?
Yes, you can use a mapped type with key remapping to iterate over the members of the union corresponding to the element type of the obj
array, and map the "key"
property to the key and the element type of the "value"
property to the value:
type Tee = { [O in typeof obj[number] as O["key"]]: O["value"][number] }
/* type Tee = {
fruit: "apple" | "banana";
meat: "pork" | "chicken";
} */
Note that you need the typeof
type operator to get the type of the obj
value, and you need indexed access types to get the type of a value at a particular type of key. So if O
is an object with key
and value
properties, then O["key"]
is the type of the key
property and O["value"]
is the type of the value
property. And for arrays, indexing with number
(e.g., (typeof obj)[number]
or (O["value"])[number]
) gives you the element type (or a union of them, if it is a heterogeneous array).