首页 > 解决方案 > 我可以强制 TypeScript 编译器使用名义类型吗?

问题描述

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!

然而,作为实现提供者,someFunction我真的想禁止传递结构相似的对象,但我真的只想允许 MyClassTest 或其子类型的真实实例。我想至少对我自己的一些函数声明强制执行“名义类型”。

这可能吗?

背景:考虑传递给 API 的对象需要属于该类型的情况,例如,因为它们是由在该对象上设置一些内部状态的工厂生产的,并且该对象实际上具有someFunction期望按顺序存在的私有接口正常工作。但是我不想透露该私有接口(例如在打字稿定义文件中),但如果有人传入假实现,我希望它是编译器错误。具体示例:我希望打字稿编译器在这种情况下抱怨,即使我提供了这样的所有成员:

//OK for typescript, breaks at runtime
window.document.body.appendChild({nodeName:"div", namespaceURI:null, ...document.body}) 

标签: typescriptduck-typing

解决方案


没有编译器标志可以使编译器以名义方式运行,实际上原则上不能有这样的标志,因为它会破坏很多 javascript 场景。

有几种技术通常用于模拟某种名义类型。品牌类型通常用于原语(从这里选择一个作为示例),对于类,一种常见的方法是添加一个私有字段(私有字段在结构上不会被任何东西匹配,除了确切的私有字段定义)。

使用最后一种方法,您的初始样本可以写成:

// there is a class
class MyClassTest {
    private _useNominal: undefined; // private field to ensure nothing else is structually compatible.
    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")
        } 
    }
}


someFunction({foo(){}, bar(){}, _useNominal: undefined})  //err

对于您的特定场景,使用append我认为我们无法做任何我们可以做的事情,因为Node它被定义lib.d.ts为一个接口和一个const,所以用一个私有字段来增加它几乎是不可能的(不改变lib.d.ts),即使我们它是否可能会破坏许多现有的代码和定义。


推荐阅读