Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a Static Variable inside a function in Typescript?

Tags:

typescript

I know that we can declare a Static Variable or Function within a Class like this

class SomeClass(){
  static foo = 1;
  static fooBar(){ 
    return ++SomeClass.foo;
  }
}

Is there any way to declare a Static Local Variable directly inside the function something like this ?

class SomeClass(){
  fooBar(){
    static foo = 1;
    return ++this.foo;
  }
}
like image 465
Ankit Singh Avatar asked Jan 28 '16 05:01

Ankit Singh


2 Answers

Is there any way to declare a Static Local Variable directly inside the function something like this

There is no special syntax for it. But if you want a stateful function the pattern is covered here : https://github.com/basarat/typescript-book/blob/master/docs/tips/statefulFunctions.md

For your example:

class SomeClass {
    fooBar = (new class {
        foo = 1;
        inc = () => this.foo++;
    }).inc
}

let foo = new SomeClass();
console.log(foo.fooBar()); // 1
console.log(foo.fooBar()); // 2
like image 179
basarat Avatar answered Oct 04 '22 03:10

basarat


This isn't possible. You can declare the static in the class, but not in a function body.

like image 32
Ryan Cavanaugh Avatar answered Oct 04 '22 04:10

Ryan Cavanaugh