1

I have some code similar to the following and TypeScript complains about the property __cache: Property '__cache' does not exist on type '() => number'.(2339)

function getNextValue(): number {
   if (typeof getNextValue.__cache === 'undefined') {
      getNextValue.__cache = 0;
   }

   return ++getNextValue.__cache;
}

How can this be correctly typed to declare a property __cache: number|undefined ?

doberkofler
  • 9,511
  • 18
  • 74
  • 126
  • 1
    Does this answer your question? [Build a function object with properties in TypeScript](https://stackoverflow.com/questions/12766528/build-a-function-object-with-properties-in-typescript) – jonrsharpe Feb 27 '20 at 13:15

1 Answers1

2

One way to achieve the desired behaviour would be to use an arrow function instead like this:

interface NextValueFn {
  (): number
  __cache?: number;
}

const getNextValue: NextValueFn = (): number => {
   if (typeof getNextValue.__cache === 'undefined') {
      getNextValue.__cache = 0;
   }

   return ++getNextValue.__cache;
}

On Typescript Playground

Getting the same behaviour using plain functions is not possible at the moment, this issue has been raised with the typescript maintainers and is being tracked here #34319.

DAG
  • 6,710
  • 4
  • 39
  • 63