简体   繁体   中英

how to define and use static variable in typescript

I want to define a static variable called index in my function, which does such as index++. that means that if this method is called, the varaible will be added.

Typescript is just JavaScript with types, JavaScript does not have any such static function variables, so neither does Typescript.

You can use a variable defined in the parent context (such as the module context) to get something akin to what you want:

let index = 0;
function fn() {
  index++
}

fn()
console.log(index); // 1

fn()
console.log(index); // 2

Playground Link

We can use static variables in Typescript.

class Test {
    static index = 1;

    static print() {
        console.log(Test.index++);
    }
}
Test.print(); // prints 1
Test.print(); // prints 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM