UPDATED
In case of node.js and deno you need to compare with undefined instead of Window
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this === undefined) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe
ORIGINAL
The right way in TS is to use classes instead of prototype. Then you don't need to tackle this problem.
class Fool {
constructor(public name: string) {}
greet() {
console.log(`Fool greets ${this.name}`);
}
}
new Fool("Joe").greet(); // Fool greets Joe
If you still want to use prototype, what isn't recommended, you can do a hotfix:
interface Fool {
greet(): any;
}
function Fool(this: any, name: string): Fool {
if (this.constructor === Window) { // check if it was called statically.
return new (Fool as any)(name);
}
this.name = name;
return this;
}
Fool.prototype.greet = function () {
console.log(`Fool greets ${this.name}`);
};
Fool("Joe").greet(); // Fool greets Joe
new?