【发布时间】: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