我在使用带有严格模式的14号角的trackBy时遇到了问题:True,

这是代码(它的工作方式类似于严格模式下的charme:FALSE)

App.Component.html:

<div *ngFor="let item of items; index as i; trackBy: trackByFn">
  {{ i + 1 }} {{item.name}}
</div>


<br>

<button (click)="addSomething()">Load Data</button>

App.components.ts

import { Component } from '@angular/core';

interface DemoArray {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'angular-sandbox';

  public items: DemoArray[] = [
    { id: 0, name: 'Apfel' },
    { id: 1, name: 'Mango' },
    { id: 2, name: 'Birne' },
  ];

  public addSomething(): void {
    this.items = [
      { id: 0, name: 'Apfel' },
      { id: 1, name: 'Mango' },
      { id: 2, name: 'Birne' },
      { id: 3, name: 'Kiwi' },
      { id: 4, name: 'Mandarine' },
      { id: 5, name: 'Banane' },
    ];
  }

  trackByFn(item) {
    return item.id;
  }
}

使用严格模式:True并将trackByFn更改为:

  trackByFn(item: { id: any }) {
    return item.id;
  }

VSCode说:

类型‘(Item:{id:any;})=&gt;any’不可赋值给类型‘TrackByFunction’.ngtsc(2322) App.Component.ts(8,44):组件AppComponent的模板出错.

推荐答案

Angular 上的严格模式使以下事物成为可能

  • 在打印脚本中启用严格模式
  • 严格Angular 编译器strictTemplatesstrictInjectionParametersstrictInputAccessModifiers
  • 减少Bundle 包大小预算

因为模板上的strictTemplates个类型严格判断它的类型,就像它在TypeScrip中所做的那样.

现在,在这种情况下,trackBy,我们超过了TrackByFunction.当前写入的trackByFn不遵循类型TrackByFunction.

interface TrackByFunction<T> {
  <U extends T>(index: number, item: T & U): any
}

因此,trackByFn函数应该遵循TrackByFunction接口签名.

trackByFn(index: number, item: { id: any }) {
   return item.id;
}

Typescript相关问答推荐

如何在方法中定义TypeScript返回类型,以根据参数化类型推断变量的存在?

TypeScript类型不匹配:在返回类型中处理已经声明的Promise Wrapper

单击并移除for循环中的一项也会影响另一项

当方法参数和返回类型不相互扩展时如何从类型脚本中的子类推断类型

在分配给类型的只读变量中维护const的类型

react 路由Use RouteLoaderData类型脚本错误

路由链接始终返回到

为什么Typescript不能推断类型?

如何在方法中正确地传递来自TypeScrip对象的字段子集?

TypeScrip错误:为循环中的对象属性赋值

自动通用回调

如何编辑切片器以使用CRUD调用函数?

map 未显示控制台未显示任何错误@reaction-google-map/api

在抽象类构造函数中获取子类型

打字:注解`是字符串`而不是`布尔`?

我应该使用服务方法(依赖于可观察的)在组件中进行计算吗?

React router - 如何处理嵌套路由?

如果父级被删除或删除,如何自动删除子级?

有没有办法将类型与关键更改相匹配?

为什么我们在条件语句中使用方括号[]?