TypeScript使用结构子类型,因此实际上是有可能的:
// 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!
然而,作为一名实施提供者,我想禁止传递结构类似的对象,但我只想允许MyClassTest或其子类型的真实实例。我至少想强制执行“命名类型”在我的某些函数声明中。这是否可能?背景:考虑一个情况,API所需的对象必须是该类型,例如因为它们由设置了该对象的某些内部状态的工厂生产,并且该对象实际上具有
someFunction
希望存在以便正常工作的私有接口。然而,我不想透露该私有接口(例如在typescript定义文件中),但如果有人传入假实现,则希望它成为编译器错误。具体示例:在此情况下,即使我提供了所有成员,我也希望typescript编译器抱怨。//OK for typescript, breaks at runtime
window.document.body.appendChild({nodeName:"div", namespaceURI:null, ...document.body})
unique
关键字,可以帮助创建品牌类型。 - Sebastian