TypeScript 错误:即使在定义类型之后,参数“element”在 forEach 循环中隐式具有“any”类型

问题描述 投票:0回答:1

我正在 Visual Studio Code 中处理 TypeScript 项目,并且遇到了 forEach 循环中参数类型的问题。这是我的 search-car.component.ts 文件中的相关代码片段:

searchCar() {
  console.log(this.validateForm.value);
  this.isSpinning = true;
  this.adminService.searchCar(this.validateForm.value).subscribe((res) => {
    res.carDtoList.forEach(element) => {
      element.processedImg = 'data:image/jpeg;base64,' + element.returnedImg;
      this.cars.push(element);
    });
    console.log(res)
    this.isSpinning = false;
  })
}

我试过了

res.carDtoList.forEach((element:any) => {

但它返回另一个错误: X [错误] TS7006:参数“元素”隐式具有“任意”类型。 [插件角度编译器]

src/app/modules/customer/components/search-car/search-car.component.ts:38:29:
  38 │       res.carDtoList.forEach(element => {
angular typescript rxjs typechecking
1个回答
0
投票

您需要为

Car
创建一个接口,其中包含该对象的所有属性。

export interface Car {
    name: string;
    ...
}

然后使用此接口并将

element
的类型设置为
Car
这将解决您的问题!

...
cars: Array<Car> = [];

searchCar() {
  console.log(this.validateForm.value);
  this.isSpinning = true;
  this.adminService.searchCar(this.validateForm.value).subscribe((res) => {
    res.carDtoList.forEach((element: Car) => { // <- changed here!
      element.processedImg = 'data:image/jpeg;base64,' + element.returnedImg;
      this.cars.push(element);
    });
    console.log(res)
    this.isSpinning = false;
  })
}

另一种选择是只定义元素的

any
类型

...
res.carDtoList.forEach((element: any) => {
...
© www.soinside.com 2019 - 2024. All rights reserved.