0

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'
1
  • The property state doesn't exist on your function. It would exist on newly constructed objects using someMethod as a constructor (i.e. new someMethod(true)), but not on the function. Commented Mar 1, 2019 at 18:32

1 Answer 1

1

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 = {};
Sign up to request clarification or add additional context in comments.

1 Comment

I sort of chalked this up to a bad pattern in the first place. Good to have reaffirmation and thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.