Home > Software design >  angular Property 'appareilStatus' has no initializer and is not definitely assigned in the
angular Property 'appareilStatus' has no initializer and is not definitely assigned in the

Time:10-22

hi everyone ,i'am begginer in the angular framework , i created the first component,but got an error someone can help me please,

enter image description here

here is the error in the console log

enter image description here

CodePudding user response:

mate! Welcome on board!

The error is thrown by the linter due to the TypeScript rule strictPropertyInitialization. See: https://www.typescriptlang.org/tsconfig#strictPropertyInitialization

When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor.

The problem with your code is that you've type the appareilStatus as a string, but did not make sure that the variable is actually defined. In the case that your component appareilStatus is used without the input, that variable will be undefined and therefore not a string.

<app-appareil></app-appareil>
instead of your intended
<app-appareil appareilStatus="..." [appareilName]="'...'"></app-appareil>

To solve this error you have multiple options:

  1. Add undefined to the types: @Input() appareilStatus: string | undefined
  2. Mark appareilStatus as an optional parameter @Input() appareilStatus?: string
  3. Initialize your variable with a default value: @Input() appareilStatus: string = ''
  4. Initialize your variable in the constructor
@Input() appareilStatus: string

constructor() {
  this.appareilStatus = 'add your logic here';
}
  1. Not recommended: suppress the error in that line by adding // @ts-ignore in the line before
  2. Use a non-null assertion and mark your variable as "never undefined" if you intend this field as a required input: @Input() appareilStatus: string

or... if you are annoying by this rule for now. You can disable this check by adding "strictPropertyInitialization": false to your tsconfig.json

CodePudding user response:

This is due to something called strictPropertyInitialization which is equal to true in tsconfig.json.

So we have to tell the compiler that this instance will be initialized during runtime.

We do that by adding the ! operator to ignore strict type.

Your declaration will become like the following

@Input() appareilName!: string;

Hope this helped.

  • Related