打字稿:表达函数实例属性

时间:2019-03-01 18:23:28

标签: javascript typescript

赋予JS函数

function someMethod (arg1: boolean) {
  this.state = { };

  // logic and stuff
  return arg1;

如何在打字稿中表达state

someMethod(true);
someMethod.state; // Property 'state' does not exist on type '(arg1: boolean) => boolean'

1 个答案:

答案 0 :(得分:1)

如果您希望someMethod是具有属性的普通函数,则可以简单地将其声明为具有呼叫签名和属性,如下所示:

declare const someMethod: {
  (arg1: boolean): boolean;
  state: any; // or whatever type you intend someMethod.state to have
}

但是,如果实际上将someMethod用作构造函数,则强烈建议改写为class

declare class someClass {
  constructor(arg1: boolean);
  state: any;
}

然后像这样使用它(注意new关键字):

const instance = new someClass(true);
instance.state = {};