dook
dook

Reputation: 1243

Typescript: express function instance property

Given a JS function

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

  // logic and stuff
  return arg1;

How can state be expressed in Typescript?

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

Upvotes: 0

Views: 129

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

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:

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:

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

And then use it like this (note the new keyword):

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

Upvotes: 1

Related Questions