首页 > 解决方案 > 打字稿中的类型函数原型

问题描述

打字稿:如何为带有原型的函数添加类型?

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'.`;

标签: node.jstypescriptts-node

解决方案


new如果用西装构造实例:

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();

推荐阅读