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;
}
}
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
This isn't possible. You can declare the static in the class, but not in a function body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With