【发布时间】:2019-03-21 13:08:48
【问题描述】:
TypeScript 使用structural subtyping,所以这实际上是可能的:
// there is a class
class MyClassTest {
foo():void{}
bar():void{}
}
// and a function which accepts instances of that class as a parameter
function someFunction(f:MyClassTest):void{
if (f){
if (!(f instanceof MyClassTest)) {
console.log("why")
}
}
}
// but it's valid to pass objects, which aren't in fact instances
// they just need to "look" the same, be "structural subtypes"
someFunction({foo(){}, bar(){}}) //valid!
但是,作为someFunction 的实现提供者,我确实想禁止传递结构相似的对象,但我真的只想允许 MyClassTest 或其子类型的真实实例。我想至少对我自己的一些函数声明强制执行“名义类型”。
这可能吗?
背景:考虑传递给 API 的对象需要属于该类型的情况,例如因为它们是由在该对象上设置一些内部状态的工厂生产的,并且该对象实际上具有someFunction 期望在那里才能正常工作的私有接口。但是我不想透露该私有接口(例如在打字稿定义文件中),但如果有人传入假实现,我希望它是编译器错误。具体示例:我希望打字稿编译器在这种情况下抱怨,即使我提供了所有这样的成员:
//OK for typescript, breaks at runtime
window.document.body.appendChild({nodeName:"div", namespaceURI:null, ...document.body})
【问题讨论】: