简体   繁体   English

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

[英]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.

相关问题 使用TypeScript添加属性以实现功能 - Adding property to function with TypeScript TypeScript - 使用构造函数属性创建实例 - TypeScript - Create an instance using the constructor property Typescript接口,为动态第二个属性引用一个实例属性 - Typescript Interface, reference one instance property for dynamic second property 具有object属性的新函数实例 - New instance of function with object property 使用 Typescript 时如何在 Express req object 中添加自定义属性 - How to add custom property in Express req object when using Typescript TypeScript:覆盖不相关类中的实例函数 - TypeScript: Overwrite instance function in unrelated class 创建对象/函数实例,将JavaScript转换为TypeScript - Create instance of object/function convert JavaScript to TypeScript 在实例对象内部的函数中获取类的实例(this)-Typescript / Angular - Get instance of class (this) in function inside instance object - typescript/angular 根据 Typescript Angular 中的类型为类实例属性分配一个值 - Assign class instance property a value based on its type in Typescript Angular (Typescript)不在类实例的子属性上调用Setter - (Typescript) Setter is not called on a sub-property of a class instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM