Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 联合类型的部分键,作为typescript中对象的键_Javascript_Typescript_Types - Fatal编程技术网

Javascript 联合类型的部分键,作为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: '

我想使用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: '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",
};