Ankit Singh
Ankit Singh

Reputation: 24945

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;
  }
}

Upvotes: 20

Views: 20889

Answers (4)

Trass3r
Trass3r

Reputation: 6287

Improving on @realh's answer I was able to solve it all inside the class:

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

The this parameter is the crucial piece to access the class fields.

Upvotes: 2

realh
realh

Reputation: 1121

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.

Upvotes: 4

basarat
basarat

Reputation: 276269

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

Upvotes: 11

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220944

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

Upvotes: 17

Related Questions