Sunday 12 December 2021

3 Ways to fix Property '..' has no initializer and is not definitely assigned in the constructor.ts

 Let’s say you have following Person class written in Typescript

class Person {
name: string
}

With name keyword underlined in red color, VSCode gives following warning

Property name has no initializer and is not definitely assigned in the constructor.ts


Let’s say you have following Person class written in Typescript

class Person {
name: string
}

With name keyword underlined in red color, VSCode gives following warning

Property name has no initializer and is not definitely assigned in the constructor.ts

It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor.

How do we fix this?

Approach 1

Set name property to empty string

class Person {
name: string = ''
}

Approach 2

If the variable is passed as input while instantiating class, you can initialize it inside constructor

class Person {
constructor(name: string) {
this.name = name
}
name: string
}

Approach 3

Add the ! as a postfix to the variable name as follows

class Person {
name!: string
}

When you add an exclamation mark after variable/property name, you’re telling to TypeScript that you’re certain that value is not null or undefined.

You can also get rid of warning by setting strictPropertyInitialization: false inside tsconfig.json

No comments:

Post a Comment