TypeScript中将联合类型的部分键作为对象的键

10
我希望将联合类型的键作为 TypeScript 对象中的键使用。
type EnumType = 'a1' | 'a2'

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


在这种情况下,我必须将a2作为对象的键添加。是否有一种方法使其变为可选? Playground
2个回答

22

只需要像这样加上一个问号:

type EnumType = 'a1' | 'a2'

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

您当前代码中的object定义:

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

成为:

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

允许每个键都是可选的。


14

请使用Utility Types

type EnumType = "a1" | "a2";

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


2
大约一个小时前,我尝试了类似于Record<Partial<EnumType>, string>>的东西,但它没有编译。然而,正如你所指出的,将Partial<>放在外面而不是键周围可以解决问题。也许是我自己的问题,但是:1. 我觉得这不直观或逻辑(我想要KEY是部分的,而不是整个记录);2. 实用程序类型文档页面不够详细,无法说明这是正确的语法。令人沮丧。感谢@ZOFFY提供答案。 - Joseph Beuys' Mum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接