Definite Assignment Assertions

The definite assignment assertion is a feature that allows a ! to be placed after instance property and variable declarations to relay to TypeScript that a variable is indeed assigned for all intents and purposes, even if TypeScript’s analyses cannot detect so.

For example:

  1. let x: number;
  2. initialize();
  3. console.log(x + x);
  4. // ~ ~
  5. // Error! Variable 'x' is used before being assigned.
  6. function initialize() {
  7. x = 10;
  8. }

With definite assignment assertions, we can assert that x is really assigned by appending an ! to its declaration:

  1. // Notice the '!'
  2. let x!: number;
  3. initialize();
  4. // No error!
  5. console.log(x + x);
  6. function initialize() {
  7. x = 10;
  8. }

In a sense, the definite assignment assertion operator is the dual of the non-null assertion operator (in which expressions are post-fixed with a !), which we could also have used in the example.

  1. let x: number;
  2. initialize();
  3. // No error!
  4. console.log(x! + x!);
  5. function initialize() {
  6. x = 10;

In our example, we knew that all uses of x would be initialized so it makes more sense to use definite assignment assertions than non-null assertions.