Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type function prototype in typescript

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'.`;
like image 499
user3599894 Avatar asked Sep 02 '25 04:09

user3599894


1 Answers

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();
like image 131
Vitaly Kuznetsov Avatar answered Sep 05 '25 00:09

Vitaly Kuznetsov