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 theconstructor.ts
It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor.
Set name property to empty string
class Person { name: string = '' }
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 }
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