我想将并集类型的键用作打字稿中对象的键。
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'
}
object
当前代码的定义:
const object: {
a1: string | undefined;
a2: string | undefined;
}
成为:
const object: {
a1?: string | undefined;
a2?: string | undefined;
}
允许每个键都是可选的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句