繁体   English   中英

typescript 中的 function 原型

[英]Type function prototype in typescript

Typescript:如何使用原型为 function 添加类型?

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

如果用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();

更新

在 node.js 和 deno 的情况下,您需要与undefined而不是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

原来的

TS 中的正确方法是使用类而不是prototype 那么你不需要解决这个问题。

class Fool {
  constructor(public name: string) {}

  greet() {
      console.log(`Fool greets ${this.name}`);
  }  
}

new Fool("Joe").greet(); // Fool greets Joe

如果你仍然想使用原型,不推荐的,你可以做一个修补程序:

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

使用此解决方案,您可以同时使用Fool(name)new Fool(name)

interface Fool {
  name: string;
  greet(): void;
}

interface FoolConstructor {
  new(name: string): Fool;
  (name: string): Fool;
}

const Fool = function (this: Fool | void, name: string): Fool {
  if (!(this instanceof Fool)) {
    return new Fool(name);
  }

  this.name = name;
  return this;
} as FoolConstructor;

Fool.prototype.greet = function(this: Fool) {
  console.log(`Fool greets ${this.name}`);
};

console.log(
  new Fool('Joe').greet(),
  Fool('Joe').greet()
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM