联合类型的部分键作为打字稿中对象的键

时间:2020-10-22 12:12:33

标签: javascript typescript types

我想使用联合类型的键作为打字稿中对象的键。

type EnumType = 'a1' | 'a2'

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

在这种情况下,我必须在对象中甚至添加a2作为键。有没有办法使它可选?

Playground

2 个答案:

答案 0 :(得分:2)

请使用Utility Types

type EnumType = "a1" | "a2";

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

答案 1 :(得分:1)

只需添加一个问号:

type EnumType = 'a1' | 'a2'

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

带有当前代码的object定义:

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

成为:

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

允许每个键都是可选的。