[Typescript] Static block for Class

In recent Typescript, it is possible to define static block

class Car {
    static nextSerialNumber = 100
    static isReady = false
    static {
        // this is the static field
        fetch('https://get-next-serial-number.com')
            .then(res => res.json())
            .then(data => {this.nextSerialNumber = data.mostRecentInvokedId + 1})
            .finally(() => {
              this.isReady = true
            })
    }
}

 

When the static block run?

It runs as soon as the Class definition runs.

So it might run before we create a new class instances if it is sync operation.

For async operation you might need a signal isReady to indicate everything is ready.

posted @ 2024-01-16 16:17  Zhentiw  阅读(6)  评论(0编辑  收藏  举报