user7898461
user7898461

Reputation:

Add warning if field is undefined before use in constructor

I have this code:

  @Input() myUuid;
  private dcs: HistoryService;

  constructor(private hsf: HistoryServiceFactory) {
    console.log('my uuid:', this.myUuid.toString());
  }

TypeScript does not give a warning here, as far as I can tell:

enter image description here

but myUuid should always be undefined, since it will only be guaranteed to be initialized after ngOnInit() is fired. Would it be possible for TS to know this and display a (compilation) warning?

Upvotes: 0

Views: 123

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31873

Update TypeScript to the latest version. 2.7 introduced exactly this functionality: checks for definite assignment.

This is documented at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html

Specifically:

TypeScript 2.7 introduces a new flag called --strictPropertyInitialization. This flag performs checks to ensure that each instance property of a class gets initialized in the constructor body, or by a property initializer. For example

Make sure you are use --strict

Note that if you have properties that you want to leave uninitialized after construction, you will now need to mark them as optional (property?). This was always a good practice in such cases but is now enforced.

Upvotes: 3

Related Questions