最近我考虑将我的一个副业项目转换成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 };
// Function in another file calling Foo
import { Foo } from './file';
function getSum() {
let foo = new Foo(); // I got the below error here!!!
foo.set();
}
当我尝试输入时,出现了以下错误:'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
查看TypeScript文档后,我理解应该按以下方式编写调用签名:
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
但我不知道如何将上述类型应用于我的“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;
};
在导入/导出或函数调用时,我无法应用它。以下所有情况都会抛出错误。
export { Foo: FooConstructor };
import { Foo: FooConstructor } from './file';
let foo = new Foo() as FooConstructor;
那我是不是必须将Foo函数改写为一个类,这是唯一的方法吗?!我看到很多博客介绍了如何编写一个类。但即便采用那种方法,我还是会收到一个错误信息:Type 'FooType' is not assignable to type 'FooConstructor'
。
我感到有些迷惑。任何帮助都将不胜感激!
编辑:我的File.ts文件现在看起来像这样:
我在File.ts文件中添加了声明,就像这样:
type FooType = {
x: number,
y: number,
};
declare class Foo {
constructor();
x: number;
y: number;
setHeader(): number;
}
function Foo(this: FooType) {
this.x = 1;
this.y = 2;
}
Foo.prototype.set = function(): number {
return this.x + this.y;
};
export { Foo };
file.js
的文件旁边附加一个同名的声明文件file.d.ts
,其内容如下:export declare class Foo { constructor(x: number, y: number); set(): number; }
。 - Aluan Haddadx
和y
:declare class Foo { constructor(); set(): number; x: number; y: number; }
https://tsplay.dev/WJ98lm - Linda Paistefile.d.ts
中添加上述声明。但是在需要调用 Foo 的文件中仍然出现了'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
的错误提示。 - Amith Raravi