给定一个 JS 函数
function someMethod (arg1: boolean) {
this.state = { };
// logic and stuff
return arg1;
如何在 Typescript 中表达状态
?
someMethod(true);
someMethod.state; // Property 'state' does not exist on type '(arg1: boolean) => boolean'
最佳答案
如果您希望 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 = {};
关于javascript - Typescript:表达函数实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54950273/