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

By Gulshan Saini
Published in Typescript
February 18, 2021
1 min read

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


Previous Article
How to check if a string contains a substring in JavaScript?

Related Posts

(Solved) Cannot find name '..'. Do you need to change your target library?
February 28, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media