这是 TypeScript 手册 here 中提到的示例-
Hybrid Types
As we mentioned earlier, interfaces can describe the rich types present in real world JavaScript. Because of JavaScript’s dynamic and flexible nature, you may occasionally encounter an object that works as a combination of some of the types described above.
One such example is an object that acts as both a function and an object, with additional properties:
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
如果我将函数 getCounter 中的类型转换行修改为此,编译器仍然会验证它是否正确。
let counter = <Counter>{ };
但是如果你运行编译后的 JavaScript,它会给出错误,因为 counter 现在并不是真正的函数,而是一个对象。
问题 - TypeScript 编译器在这种情况下是否应该给出任何错误,或者它是否正确,因为函数是对象的子类型?
编辑器的链接是 here
最佳答案
类型断言用于告诉编译器忽略它所知道的类型,而选择您告诉它的类型。如果您做出的断言是错误的,编译器无法警告您。当您需要执行此操作时,Typescript 中肯定有类型,但如果您能找到一种类型安全的方法来执行等效操作,那就更好了。在这种情况下,您可以使用Object.assign
:
function getCounter(): Counter {
let counter = Object.assign(function (start: number) { return ""}, {
interval: 123,
reset: function () { }
});
return counter;
}
关于typescript - 混合接口(interface)中的类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49187662/