赋予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'
答案 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 = {};