A_Singh A_Singh - 4 months ago 19
TypeScript Question

How to declare a Static Variable inside a function in 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;
}
}

Answer

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
Comments