[英]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.在这种情况下,我甚至必须添加 a2 作为对象中的键。 Is there a way to make this optional?
有没有办法让它成为可选的?
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:使用当前代码的
object
定义:
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",
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.