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

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


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

I think there's a problem in @basarat's answer. Add this:

let bar = new SomeClass();
console.log(bar.fooBar());

The result is 1 because fooBar is not a method, but a field that happens to be a function. Therefore each instance of SomeClass has its own closure for fooBar with its own distinct foo.

I think that to truly emulate a static local variable as in C++, the answer should be 3, because the one method and one foo are shared by all instances. To do this in Typescript you could instead define fooBar after the rest of the class:

SomeClass.prototype.fooBar = (function() {
    let foo = 1;
    function fooBar() {
        return foo++;
    }
    return fooBar;
})();

I've also used a different idiom to create the closure, avoiding the introduction of a new class and not using arrow notation. In case fooBar ever needs to access members of an instance, now there won't be any confusion over what this refers to.

If necessary I guess you could also include a dummy definition of fooBar() in the class body to satisfy type checking; the subsequent external definition should simply overwrite it.

Tags:

Typescript