简体   繁体   中英

Partial keys of union type as key of an object in typescript

I want to use the keys of the union type as key of the object in typescript.

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]: string}= {
 a1: 'test'
}

In this case I have to add even a2 as a key in the object. Is there a way to make this optional?

Playground

Just add a question mark like this:

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]?: string}= {
 a1: 'test'
}

The object definition with your current code:

const object: {
    a1: string | undefined;
    a2: string | undefined;
}

Becomes:

const object: {
    a1?: string | undefined;
    a2?: string | undefined;
}

Allowing every key to be optional.

please useUtility Types

type EnumType = "a1" | "a2";

const object: Partial<Record<EnumType, string>> = {
  a1: "test",
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM