[英]Restricting an interface to specific keys from a union type
我有一个联合类型列出了一些允许的键: type AllowedKeys = "a" | "b";
type AllowedKeys = "a" | "b";
在其他地方,我正在声明一个接口,并且我想将此接口限制为允许的键:
interface Interface {
a: Something; // This is fine
c: SomethingElse; // I want this to throw an error
}
我怎么能写这个来强制接口尊重允许的键?
你不能用interface做到这一点,因为
这是因为 TypeScript 中的接口是开放式的。 这是 TypeScript 的一个重要原则,它允许您使用接口模仿 JavaScript 的可扩展性。
基本上,您总是可以向界面添加新属性。
相反,您可以尝试
type AllowedTypes = {
"a" : string;
"b": number ;
}
type AllowedKeys = keyof AllowedTypes;
如果您不需要将其作为接口并且可以使用 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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.