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


This post talks about different ways to solve below error in Angular and typescript

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

For example, In 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 below line of code

  selectedRoles: any[];

What does the error mean?

This is valid compilation error to avoid run time error.

You declared variable but not initialzied with default values.

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

There are 4 ways to fix an compilation error.

1.Initialize the variable in constructor

In this, class properties are initialized in constructor

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

StrictPropertyInitialzer is an typescript rule released in typescript 2.7 version.

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

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

This enables to disable all validation rules in angular application.

{
    "compilerOptions"{
    "strictPropertyInitialization": false
    }
}
  1. adding Definite Assignment Assertions in Angular property Definite Assignment Assertions is an typescript feature to make it property or variable has value aviable at runtime.

just add ! symbole to variable or property

  selectedRoles!: any[];
  1. Adding undefined to variable initialization

Whenever variable is declared and compiler not found the value, It defaults to undefined value

selectedRoles: any[] | undefined
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.