Javascript 联合类型的部分键,作为typescript中对象的键
我想使用union类型的键作为typescript中对象的键Javascript 联合类型的部分键,作为typescript中对象的键,javascript,typescript,types,Javascript,Typescript,Types,我想使用union类型的键作为typescript中对象的键 type EnumType = 'a1' | 'a2' const object:{[key in EnumType]: string}= { a1: 'test' } 在这种情况下,我必须添加a2作为对象中的键。有没有办法让它成为可选的 只需添加一个问号,如下所示: type EnumType = 'a1' | 'a2' const object:{[key in EnumType]?: string}= { a1: '
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]: string}= {
a1: 'test'
}
在这种情况下,我必须添加a2作为对象中的键。有没有办法让它成为可选的
只需添加一个问号,如下所示:
type EnumType = 'a1' | 'a2'
const object:{[key in EnumType]?: string}= {
a1: 'test'
}
包含当前代码的对象定义:
const object: {
a1: string | undefined;
a2: string | undefined;
}
变成:
const object: {
a1?: string | undefined;
a2?: string | undefined;
}
允许每个键都是可选的。请使用
type EnumType=“a1”|“a2”;
常量对象:部分={
a1:“测试”,
};
type EnumType = "a1" | "a2";
const object: Partial<Record<EnumType, string>> = {
a1: "test",
};