[英]Typescript: express function instance property
Given a JS function 给定一个JS函数
function someMethod (arg1: boolean) {
this.state = { };
// logic and stuff
return arg1;
How can state
be expressed in Typescript? 如何在Typescript中表达
state
?
someMethod(true);
someMethod.state; // Property 'state' does not exist on type '(arg1: boolean) => boolean'
If you want someMethod
to be a normal function that also has a property, you could simply declare it as having both a call signature and properties, like this: 如果您希望
someMethod
是具有属性的普通函数,则可以简单地将其声明为具有调用签名和属性,如下所示:
declare const someMethod: {
(arg1: boolean): boolean;
state: any; // or whatever type you intend someMethod.state to have
}
However, if someMethod
is actually meant to be used as a constructor function, I'd strongly recommend rewriting this as a class instead: 但是,如果实际上要将
someMethod
用作构造函数,则强烈建议将其重写为类 :
declare class someClass {
constructor(arg1: boolean);
state: any;
}
And then use it like this (note the new
keyword): 然后像这样使用它(注意
new
关键字):
const instance = new someClass(true);
instance.state = {};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.