HI WELCOME TO SIRIS

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

Leave a Comment

 608

in my Angular app i have a component:

import { MakeService } from './../../services/make.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-vehicle-form',
  templateUrl: './vehicle-form.component.html',
  styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
  makes: any[];
  vehicle = {};

  constructor(private makeService: MakeService) { }

  ngOnInit() {
    this.makeService.getMakes().subscribe(makes => { this.makes = makes
      console.log("MAKES", this.makes);
    });
  }

  onMakeChange(){
    console.log("VEHICLE", this.vehicle);
  }
}

but in the "makes" property I have a mistake. I dont know what to do with it...

mistake


Just go to tsconfig.json and set

"strictPropertyInitialization": false

to get rid of the compilation error.

Otherwise you need to initialize all your variables which is a little bit annoying


A. If you are using VSCode you need to change the TS version that the editor use.

B. Just initialize the array when you declare it

makes: any[] = [];

or inside the constructor:

constructor(private makeService: MakeService) { 
   // Initialization inside the constructor
   this.makes = [];
}

It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add the ! as a postfix to the variable name:

makes!: any[];




0 comments:

Post a Comment

Note: only a member of this blog may post a comment.