admin管理员组

文章数量:1125904

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?

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?

Share Improve this question asked Jan 9 at 2:03 kkh.namekkh.name 154 bronze badges 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Bot Commented Jan 9 at 2:44
Add a comment  | 

1 Answer 1

Reset to default 2

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).

Playground link to code

本文标签: mapped typesIs there way to declare using the value as a key in typescriptStack Overflow