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 definitely assigned to the constructor.
It is a typescript compilation error and because of this, Runtime error is avoided
Typescript 2.7 provides 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 variable, but not initialized with default values.
That means selectedRoles
declared in the component of any
array type, but not initialized this in the component.
There are 4 ways to fix a compilation error.
- Initialize the variable in constructor
In this, class properties are initialized in 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 to disable 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 property or variable has value available at runtime.
just add !
symbol to 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 application.