在我的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。json文件,在“compilerOptions”中添加:

"strictPropertyInitialization": false,

其他回答

另一种修复变量必须保持未初始化(在运行时处理)情况的方法是在类型中添加undefined(这实际上是由VC Code建议的)。例子:

@Input() availableData: HierarchyItem[] | undefined;
@Input() checkableSettings: CheckableSettings | undefined;

根据实际使用情况,这可能会导致其他问题,因此我认为最好的方法是尽可能初始化属性。

转到你的tsconfig。Json文件,并更改属性:

 "noImplicitReturns": false

然后加上

 "strictPropertyInitialization": false

在"compilerOptions"属性下。

你的tsconfig。Json文件应该是这样的:


{
      ...
      "compilerOptions": {
            ....
            "noImplicitReturns": false,
            ....
            "strictPropertyInitialization": false
      },
      "angularCompilerOptions": {
         ......
      }  
 }

希望这能有所帮助!!

祝你好运

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

2021年更新:

有一个属性像"strictPropertyInitialization"

只需转到tsconfig。Json和set

“严格”:假的

来消除编译错误。

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

这个错误背后的原因是:

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

遵循2个步骤来解决这个问题:

"strictPropertyInitialization": tsconfig.json中的错误条目 ctrl+c在终端上停止你的服务器(检查终端,它在哪里运行),然后用你使用的命令再次运行它,比如ng serve 这2个步骤,应该可以解决你的问题。因为它解决了我的问题。欢呼声……;)