Fix for Property has no initializer and is not assigned in the constructor

This post talks about different ways to solve the below errors in Angular and typescript.

error TS2564: Property ‘selectedRoles’ has no initializer and is not definitely assigned in the constructor.

Property has no initializer and is not assigned to the constructor

It is a typescript compilation error and because of this, a Runtime error is avoided

Typescript 2.7 provides a strictPropertyInitialization flag to initialize the default values for each variable declared

For example, In the Angular component.

import { Component, OnInit } from "@angular/core";
import Role from "../model/Role";

@Component({
  selector: "app-listbox-checkbox",
  templateUrl: "./listbox-checkbox.component.html",
  styleUrls: ["./listbox-checkbox.component.scss"],
})
export class ListboxCheckboxComponent implements OnInit {
  title = "Primeng listbox checkbox example";
  roles: Role[];
  selectedRoles: any[];
  constructor() {
    this.roles = [
      { name: "Administrator", value: "ADMIN" },
      { name: "Sales", value: "SALE" },
      { name: "Marketing", value: "MKT" },
      { name: "HR", value: "HR" },
      { name: "Finance", value: "FIN" },
    ];
  }
  ngOnInit(): void {}
}

The above component throws an error on the below line of code

  selectedRoles: any[];

What does the error mean?

You declared the variable, but not initialized it with default values.

That means selectedRoles is declared in the component of any array type, but not initialized in the component.

There are 4 ways to fix a compilation error.

  • Initialize the variable in the constructor

In this, class properties are initialized in the constructor

  selectedRoles: any[];
  constructor() {
    this.selectedRoles = [];
  }
  • strictPropertyInitialization to false in tsconfig.json In tsconfig.json

StrictPropertyInitialzer is a typescript rule released in the typescript 2.7 version.

It tells the compiler to enable the class to have all properties or variables initialized.

if set to false, This will tell the typescript compiler to ignore all validation rules.

This enables disabling all validation rules in angular applications.

{
    "compilerOptions"{
    "strictPropertyInitialization": false
    }
}
  • adding Definite Assignment Assertions in Angular property Definite Assignment Assertions is a typescript feature to make it a property or variable have value available at runtime.

just add the ! symbol to a variable or property

  selectedRoles!: any[];
  • Adding union type with undefined to variable initialization

Whenever a variable is declared and the compiler does not find the value, It defaults to an undefined value.

selectedRoles: any[] | undefined

Conclusion

You learned how to fix error TS2564: Property ‘selectedRoles’ has no initializer and is not definitely assigned in the constructor in Angular and typescript applications.