【问题标题】:Constructor functions in TypeScript, what is missing?TypeScript 中的构造函数,缺少什么?
【发布时间】:2018-06-23 00:43:42
【问题描述】:

我试图弄清楚如何在 JS 中使用 TypeScript 提供的类型安全和旧的普通构造函数。我有一个非常简单的例子,看起来很简单,但我错过了一些东西,无法用 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 的首选方式是使用“类”,但就我而言,我想使用简单的构造函数。

【问题讨论】:

标签: javascript typescript oop


【解决方案1】:

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

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

interface IMyServiceConstructor {
  new(): IMyService;
}

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

这可以通过使用内联类型来缩短:

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

【讨论】:

  • 我在操场上试过了,但编译器还是不喜欢它:(
【解决方案2】:

是什么阻止你这样做:

class MyService {
  // declare instance method
  doSomething: (x: string) => void;

  // this is really your function
  constructor() {
    let _name = "";
    this.doSomething = (name) => {
      _name = name;
    }  
  }
}
let service = new MyService();
service.doSomething("Test Name"); 

这会发出与原始代码几乎相同的代码。它仍然使用构造函数范围的局部变量,以及实例方法而不是类方法。 (实例方法通常是frowned upon,因为您正在为每个实例创建闭包,但这取决于您。)

TypeScript 知道 MyService 是新的,并且是你想要的所有其他优点。用构造函数类型签名跳过箍并说服 TypeScript 你的函数是正确的类型对我来说似乎不值得。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2016-03-08
    • 1970-01-01
    • 2022-10-13
    • 2017-07-21
    相关资源
    最近更新 更多