Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'filteredOptions' has no initializer and is not definitely assigned in the constructor

in my Angular app i have a component:

  filteredOptions: Observable<string[]>;

Following line give the error:

Property 'filteredOptions' has no initializer and is not definitely assigned in the constructor.

28   filteredOptions: Observable<string[]>;
like image 982
tarun sharma Avatar asked Sep 10 '25 05:09

tarun sharma


1 Answers

it's because typescript 2.7.2 included a strict class checking where all properties should be declared in constructor. So to work around that you can:

  • just add a bang sign (!) like: name!:string;
  • adding "strictPropertyInitialization": false to your compiler options.
  • use filteredOptions: Observable<string[]> | undefined;
  • use filteredOptions?: Observable<string[]>

more details:

  • name!:string; : compiler trust me on this, I will guarantee that it will not be undefined (can cause unpredicted behavior)
  • "strictPropertyInitialization": false: compiler stop your strict check everywhere please
  • the last two solutions: compiler, filteredOptions might or might not have a value. In that case, it's your responsibility to handle the undefined value in your case (use ?. in your HTML templates, null and undefined check...etc.)
like image 131
Benzara Tahar Avatar answered Sep 12 '25 18:09

Benzara Tahar