我有一个联合类型,列出了一些允许的密钥:type AllowedKeys = "a" | "b";
在其他地方,我声明了一个接口,并且希望将这个接口限制在允许的键上:
interface Interface {
a: Something; // This is fine
c: SomethingElse; // I want this to throw an error
}我怎么写这个来强制接口尊重允许的键呢?
发布于 2021-01-07 12:53:22
你不能用接口做这件事,因为
这是因为TypeScript中的接口是开放的。这是TypeScript的一个重要原则,它允许您使用接口来模拟JavaScript的可扩展性。
基本上,您可以始终向接口添加新属性。
相反,你可以试试
type AllowedTypes = {
"a" : string;
"b": number ;
}
type AllowedKeys = keyof AllowedTypes;发布于 2021-01-07 13:27:56
如果您不需要将它作为一个接口,并且可以使用type,那么可以考虑这样做:
type AllowedKeys = "a" | "b";
export type TestType = {
[key in AllowedKeys]: Something;
};它将强制您在您的类型中使用这两个键-不确定这是否是您想要的东西。例如:
这将引发一个错误:
const a: TestType = {
a: 'asd',
b: 'asd',
c: 'asd'
}这很好:
const a: TestType = {
a: 'asd',
b: 'asd',
}但这也会引发一个错误:
const a: TestType = {
a: 'asd',
}如果您不关心是否使用了所有允许的键,只需在类型声明中使用?:
export type TestType = {
[key in AllowedKeys]?: string;
};https://stackoverflow.com/questions/65612236
复制相似问题