在 TypeScript 中,过多的属性检查应用于对象文字,但不会超出范围。(这是有意记录的行为。)因此:
interface Example {
id: number;
name: string;
}
// ...
function doSomething(ex: Example) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这失败了(游乐场链接):
doSomething({
id: 42,
name: "Life, the Universe, and Everything",
extra: "not allowed" // Error 2345: Object literal may only specify known properties, and 'extra' does not exist in type 'Example'.
});
Run Code Online (Sandbox Code Playgroud)
但这不是(游乐场链接):
const ex = {
id: 42,
name: "Life, the Universe, and Everything",
extra: "not allowed"
};
doSomething(ex);
Run Code Online (Sandbox Code Playgroud)
是否可以以某种方式定义接口,即使不使用对象文字,也禁止多余的属性?例如,final某种“”界面?
如果没有,它很容易在运行时完成,但如果有一种方法可以在类型定义中完成它,那将很有用。
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |