在我的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中添加这两行

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

并确保strict设置为true

其他回答

改变

fieldname?: any[]; 

:

fieldname?: any; 

这是因为typescript 2.7.2包含了严格的类检查,其中所有属性都应该在构造函数中声明。所以要解决这个问题,只需添加一个感叹号(!),比如:

name!:string;

你不能直接使用定赋断言吗?(参见https://www.typescriptlang.org/docs/handbook/release - notes/typescript 2 - 7. - html # definite-assignment-assertions)

即声明财产为使!:任何[];!确保typescript在运行时肯定会有一个值。

抱歉,我还没有在angular中尝试过,但当我在React中遇到完全相同的问题时,它对我来说很有用。

新版本的typescript引入了严格的类初始化,这意味着你需要在构造函数体中初始化类中的所有属性,或者通过属性初始化器。在typescript文档中检查它 为了避免这种情况,您可以添加(!或者?

make!: any[] or make? : any[] 

否则,如果您希望在项目中永久删除严格类检查 你可以在tsconfig中设置strictPropertyInitialization": false。json文件

" compilerOptions ": { .... “noImplicitReturns”:假的, .... “strictPropertyInitialization”:假的 },

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

 "noImplicitReturns": false

然后加上

 "strictPropertyInitialization": false

在"compilerOptions"属性下。

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


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

希望这能有所帮助!!

祝你好运