How to Fix Property ‘…’ has no initializer and is not definitely assigned in the constructor

The Property ‘…’ has no initializer and is not assigned in the constructor error occurs when the “class property is declared without a default value (or initializer), and it is also not assigned a value within the class’s constructor.”

class MyClass {
  private name: string;

  constructor() {
    // name is not assigned here
  }
}

In the above code, the name is a property of the type string. However, we’ve not given it an initial value or assigned it a value in the constructor. This can lead to issues as TypeScript is unsure if the name property will get a valid string value before it’s used.

How to fix the error

Solution 1: Disable strictPropertyInitialization flag

You can set the “strictPropertyInitialization” option to “false” in your tsconfig.json file. This will disable the check for properties being assigned in the constructor. However, this might not be the best solution, as it reduces the type of safety TypeScript provides.

{
  "compilerOptions": {
    "strictPropertyInitialization": false
  }
}

Solution 2: Initialize the property with a default value

class MyClass {
  name: string = "default value";
}

Solution 3: Assign a value to the property in the constructor

class MyClass {
  name: string;

  constructor() {
    this.name = "value assigned in constructor";
  }
}

Solution 4: Using the definite assignment assertion (!)

This tells TypeScript that the property will be assigned a value, even though it can’t verify that in the constructor. Use this option cautiously, as it may lead to runtime errors if the property is not assigned a value as expected.

class MyClass {
  name!: string;
}

Solution 5: Make the property optional

If the property has no value assigned, you can declare it optional using the ? modifier. This tells TypeScript that the property can be undefined.

class MyClass {
  name?: string;
}

Choose the approach that best fits your use case and coding style. Remember that using definite assignment assertions (option 3) or making the property optional (option 4) can lead to less type safety, so use them cautiously.

Solution 6: Assignment in the Constructor

Initialize an array when you declare it.

names: Name[];

constructor() { 
  this.names = [];
}

Conclusion

To fix the Property ‘…’ has no initializer and is not assigned in the constructor error, initialize the property with a default value, assign a value to the property in the constructor, use the definite assignment assertion (!), or make the property optional.