Thursday, May 31, 2018

TypeScript 2.7–Definite Assignment Assertions

While looking through some TypeScript 2.7 samples, I noticed the following syntax:

class User {
    // Notice the exclamation mark 
    username!: string;

    constructor(username: string) {
        this.initialize(username);
    }

    private initialize(username: string) {
        this.username = username;
    }
}
This syntax comes into play when you use another TypeScript 2.7 compiler option; strict property initialization. If the --strictPropertyInitialization flag is enabled, the type checker verifies that each instance property declared in a class either
  • has a type that includes undefined,
  • has an explicit initializer
  • is initialized within the constructor

This is problematic if you want to initialize a property within a helper method or have a dependency injection framework do it for you. To solve this situation you can use a definite assignment assertion using the exclamation mark: (!) . Now the type checker will no longer complain.

Remark: By using a definite assignment assertion it becomes your responsibility to make sure the property gets set.


No comments: