Javascript TypeScript中的构造函数缺少什么?
我试图弄清楚如何在JS中使用TypeScript提供的类型安全性和旧的普通构造函数。我有一个非常简单的示例,看起来很简单,但我遗漏了一些东西,无法使用TypeScript进行编译:Javascript TypeScript中的构造函数缺少什么?,javascript,typescript,oop,Javascript,Typescript,Oop,我试图弄清楚如何在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): voi
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的首选方法是使用“class”,但在我的例子中,我希望使用简单的构造函数。您不能真正键入函数声明(或者至少我不知道如何键入)。但是,您可以键入一个变量,并为其分配一个函数。然后我们可以定义一个构造函数类型:
interface IMyService {
doSomething(name: string): void;
}
interface IMyServiceConstructor {
new(): IMyService;
}
const MyService: IMyServiceConstructor = function(this: IMyService){
//...
};
可以通过使用内联类型进行简化:
const MyService: { new(): IMyService } = function(){
//...
};
是什么阻止了你这么做:
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");
它发出的代码几乎与原始代码相同。它仍然使用构造函数函数作用域的局部变量,以及实例方法而不是类方法。(实例方法通常是无效的,因为您正在为每个实例创建闭包,但这取决于您自己。)
TypeScript也明白,MyService
是可更新的,并且是您想要的所有其他功能。带着构造函数类型签名和让TypeScript相信你的函数是正确的类型在我看来不值得
希望能有帮助。我在操场上试过,但编译器仍然不喜欢:(在上接受答案)