K
K
Kyki42021-11-04 14:50:28
typescript
Kyki4, 2021-11-04 14:50:28

Why is there an exclamation point when declaring a TS variable?

I was reading this article and came across this code:

let exampleFunc!: (instance: Example) => number;

class Example {
  static #accessCount = 0;
  #initial: number;
  constructor(input: number) {
    this.#initial = input * 2;
  }

  static {
    exampleFunc = (instance: Example) => {
      Example.#accessCount++;

      return instance.#initial
    }
  }
}

if (exampleFunc) {
  exampleFunc(new Example(2)); // 4
}


and I can not understand why you need "!" when declaring exampleFunc:
let exampleFunc →!← : (instance: Example) => number;

since it's clearly not part of the variable name, I also don't think it says that the variable can't be null | undefined:

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2021-11-04
@Kyki4

It tells the TS compiler not to swear at an uninitialized variable. That in fact it will be initialized in some way that TS cannot track. For example, in this case, they are initialized inside a static block, and TS apparently does not understand this yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question