Recently, I've been considering converting one of my side projects to Typescript. However, I'm encountering a problem when it comes to calling functions using the 'new' keyword.
My issue arises when I try to call a function imported from another file in the following manner:
// 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(); // The error occurs at this line!!!
foo.set();
}
Every time I attempt this, I receive the following error message:
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
.
After reviewing the typescript documentation, I realized that the call signature should be structured as shown below:
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
I attempted to apply this type structure to my 'Foo' function but struggled to implement it correctly.
// 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;
};
Despite my efforts, I couldn't successfully integrate the construct signature while exporting/importing or during function calls. Every attempt resulted in errors.
export { Foo: FooConstructor };
import { Foo: FooConstructor } from './file';
let foo = new Foo() as FooConstructor;
Do I need to convert the Foo function into a class? Is that the only viable option for typing it correctly?! Many resources demonstrate how to type classes, but even with that approach, I received an error stating,
Type 'FooType' is not assignable to type 'FooConstructor'
.
I am feeling quite lost here and would appreciate any guidance!
EDIT: My File.ts now resembles the following structure:
To outline the declaration in the File.ts file, I modified it as follows:
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 };