TypeScript 中的构造函数,缺少什么?

2024-01-12

我试图弄清楚如何将 TypeScript 提供的类型安全性与 JS 中旧的普通构造函数一起使用。我有一个非常简单的示例,看起来很简单,但我错过了一些东西并且无法使用 TypeScript 进行编译:

interface IMyService {
    new(): IMyService //I'm not sure if this line should be here, I just trying to make it working...
    doSomething(name: string): void
}

function MyService(this: IMyService): void {
    let _name = ""
    this.doSomething = (name) => {
        _name = name
    }
}

//The line below won't compile and it saying:
//"new" expression, whose target lacks a construct signature, implicitly has an "any" type
let service = new MyService();
service.setName("Test Name")  

我缺少什么?我知道使用 TypeScript 的首选方式是使用“类”,但就我而言,我想使用简单的构造函数。


您无法真正键入函数声明(或者至少我不知道如何键入)。但是,您可以键入一个变量,然后为其分配一个函数。然后我们可以定义一个构造函数类型:

interface IMyService {    
  doSomething(name: string): void;
}

interface IMyServiceConstructor {
  new(): IMyService;
}

const MyService: IMyServiceConstructor = function(this: IMyService){
  //...
};

可以通过使用内联类型来简化:

const MyService: { new(): IMyService } = function(){
  //...
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript 中的构造函数,缺少什么? 的相关文章