Typescript 仅允许枚举中的值,但不要求枚举中的每个值都存在的类型
我有以下代码:Typescript 仅允许枚举中的值,但不要求枚举中的每个值都存在的类型,typescript,Typescript,我有以下代码: enum Foo { a, b, c } type Bar = { [key in keyof typeof Foo]: string; } const test: Bar = { a: 'a', b: 'b' }; 代码抱怨test变量没有c属性 如何更改条类型,使枚举中的键是可选的?您可以使用: 按实用程序类型和 类型栏=部分 使属性成为可选属性,如[输入keyof typeof Foo]?:字符串 enum Foo { a, b,
enum Foo {
a,
b,
c
}
type Bar = {
[key in keyof typeof Foo]: string;
}
const test: Bar = {
a: 'a',
b: 'b'
};
代码抱怨test
变量没有c
属性
如何更改条
类型,使枚举中的键是可选的?您可以使用:
按实用程序类型和
类型栏=部分
使属性成为可选属性,如[输入keyof typeof Foo]?:字符串代码>
enum Foo {
a,
b,
c
}
type Bar = Partial<{
[key in keyof typeof Foo]: string;
}>
const test: Bar = {
a: 'a',
b: 'b'
};
enum Foo {
a,
b,
c
}
type Bar = {
[key in keyof typeof Foo]?: string;
}
const test: Bar = {
a: 'a',
b: 'b'
};
type Bar = Partial<Record<keyof typeof Foo, string>>