Ami*_*avi 5 javascript new-operator typescript
最近我想把我的一个业余项目转换成 Typescript。但我在使用 new 调用函数时遇到了麻烦。
我试图调用从另一个文件导入的函数,如下所示:
// Function in 'file.js'
function Foo() {
this.x = 1;
this.y = 2;
}
Foo.prototype.set = function() {
return this.x + this.y;
};
export { Foo };
Run Code Online (Sandbox Code Playgroud)
// Function in another file calling Foo
import { Foo } from './file';
function getSum() {
let foo = new Foo(); // I got the below error here!!!
foo.set();
}
Run Code Online (Sandbox Code Playgroud)
当我尝试输入此内容时,出现以下错误:'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.。
查看打字稿文档,我理解调用签名应该写成如下:
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将上述类型应用于我的“Foo”函数。我尝试将构造签名应用于该函数,但无法正确放置。
// Function in 'file.js' --> renamed to 'file.tsx'
type FooType = {
x: number,
y: number,
};
type FooConstructor = {
new (): FooType
};
function Foo(this: FooType) { // How do I add FooConstructor to this?
this.x = 1;
this.y = 2;
}
Foo.prototype.set = function(): number {
return this.x + this.y;
};
Run Code Online (Sandbox Code Playgroud)
我无法在导出/导入或函数调用期间应用它。以下所有都会引发错误。
export { Foo: FooConstructor };
import { Foo: FooConstructor } from './file';
let foo = new Foo() as FooConstructor;
Run Code Online (Sandbox Code Playgroud)
那么我是否必须将 Foo 函数更改为一个类,这是唯一可能的输入方式吗?!我看到很多博客展示了如何输入类。但即使采用这种方法,我还是收到错误消息,Type 'FooType' is not assignable to type 'FooConstructor'.
我在这里迷路了。任何帮助表示赞赏!
编辑:我的 File.ts 现在看起来像这样:
我在 File.ts 文件中添加声明,如下所示:
export { Foo: FooConstructor };
import { Foo: FooConstructor } from './file';
let foo = new Foo() as FooConstructor;
Run Code Online (Sandbox Code Playgroud)
解决这种情况的唯一方法是将以下函数转换为类:
function Foo(this: FooType) { // How do I add FooConstructor to this?
this.x = 1;
this.y = 2;
}
Foo.prototype.set = function(): number {
return this.x + this.y;
};
Run Code Online (Sandbox Code Playgroud)
到:
class Foo() {
x: number;
y: number;
constructor() {
this.x = 1;
this.y = 2;
}
set (): number {
return this.x + this.y;
}
}
Run Code Online (Sandbox Code Playgroud)