Typescript: How can i add type for function with prototype?
interface Fool {
greet(): any;
}
function Fool(name: string) {
this.name = name;
}
Fool.prototype.greet = function() {
console.log(`Fool greets ${this.name}`);
};
Fool('Joe').greet();
`Property 'greet' does not exist on type 'void'.`;
If constructing the instance with new
suits:
interface Fool {
name: string;
greet(): void;
}
interface FoolConstructor {
new (name: string): Fool;
(): void;
}
const Fool = function(this: Fool, name: string) {
this.name = name;
} as FoolConstructor;
Fool.prototype.greet = function() {
console.log(`Fool greets ${this.name}`);
};
new Fool('Joe').greet();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With