在我的Angular应用中,我有一个组件:

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);
  }
}

但是在“制造”属性中我犯了一个错误。 我不知道该怎么办……


当前回答

注释tsconfig中的//"strict": true行。json文件。

其他回答

在tsconfig。json文件,在“compilerOptions”中添加:

"strictPropertyInitialization": false,

在我的情况下,它与不同的声明根据新的typescript严格的特性:

@ViewChild(MatSort, {static: true}) sort!: MatSort;

如果在tsonfig中禁用typescript新的严格特性。json和

"compilerOptions": {
  ///
  ,
  "strictPropertyInitialization":false
}

旧的Angular指南代码工作得很好

@ViewChild(MatSort) sort: MatSort;

这里有4种方法来解决这个问题 Arunkumar Gudelli (2022) https://www.angularjswiki.com/angular/property-has-no-initializer-and-is-not-definitely-assigned-in-the-constructor/

属性”……'没有初始化式,在Angular的构造函数错误修复中也没有明确赋值

解决方法1:关闭strictPropertyInitialization标志

在Angular应用中修复这个错误的简单方法是在tsconfig中的typescript编译器选项中禁用——strictPropertyInitialization标志。json文件。

"compilerOptions": {
  ///
  ,
  "strictPropertyInitialization":false
}

解决方案2:向属性添加未定义的类型

有一个未定义的属性是可以的。

因此,在声明变量时,将未定义的类型添加到属性。

employees: Employee[];

//Change to 

employees : Employee[] | undefined;

解决方案3:向属性添加明确的赋值断言

如果你知道,我们将在以后的时间点分配财产。

最好在属性中添加明确的赋值断言。也就是说,员工。

employees!: Employee[];

解决方案4:向属性添加初始化式

消除此类型错误的另一种方法是向属性添加显式初始化式。

employees: Employee[] = [];

解决方案5:在构造函数中赋值

否则,可以在构造函数中为属性赋值。

employees: Employee[];

constructor() { 
    this.employees=[];
}

最佳解决方案

2021年更新:

有一个属性像"strictPropertyInitialization"

只需转到tsconfig。Json和set

“严格”:假的

来消除编译错误。

否则你需要初始化所有的变量这有点烦人。

这个错误背后的原因是:

typescript是一种比javascript更安全的语言。 尽管这种安全性是通过启用严格特性来增强的。所以每次当你初始化一个变量时,typescript都希望它们赋一个值。

在tsconfig.json中添加这两行

"noImplicitReturns": true,
"strictPropertyInitialization": false,

并确保strict设置为true