【发布时间】:2021-11-13 05:28:54
【问题描述】:
我想我遇到了一种情况,它似乎应该导致 TS 编译器出错(但事实并非如此),我希望有人能解释原因。
在下面的代码中,我将接口Foo 传递给它接受的函数frobnicator。然后,在frobnicator 的正文中,我“删除”了bar.y 字段。在frobnicator 终止后,类型系统允许我打印bar.y(没有错误),尽管y 不再存在。
类型系统不应该禁止我将foo 传递给frobnicator,因为现在foo 不再实现Foo 接口并且TS 认为它实现了吗?
interface Foo {
bar: { x: number, y: number };
}
function frobnicator(thing: { bar: { x: number } }) {
thing.bar = { x: 1 }; // "remove" bar.y
}
const foo: Foo = { bar: { x: 1, y: 2 } };
frobnicator(foo); // The implementation "removes" bar.y
console.log(foo.bar.y); // TypeScript does not error despite bar.y missing
【问题讨论】:
标签: typescript type-systems structural-typing