如果我尝试使用 Angular 中的方括号动态访问 属性 值,Typescript 会显示错误

Typescript is showing error if I try to access the property value dynamically using square brackets in Angular

如何修复 'string' [=] 中的问题 'string' 36=]

在此处获取 ESLint 错误:元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'Client'。 在类型 'Row'

上找不到参数类型为 'string' 的索引签名

动态-table.component.html

<table>
  <tr>
    <th *ngFor="let i of headers">
      {{i.name}}
    </th>
  </tr>
  <tr *ngFor="let row of rows">
    <td *ngFor="let head of headers">
      {{row[head.name]}} <!-- Getting ESLint error here : Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Client'.
  No index signature with a parameter of type 'string' was found on type 'Row'. -->
    </td>
  </tr>
</table>

动态-table.component.ts

interface Header {
 displayName: string,
 name: string
}

interface Row {
 empId: string,
 empName: string,
 salary: string
}

@Component({
  selector: "dynamic-table",
  templateUrl: "./dynamic-table.component.html",
  styleUrls: []
})
export class DynamicTableComponent {
  title = "Dynamic Table";

  headers: Header[] = [];
  rows: Row[] = [];

  constructor() {
    this.headers = [
      {
        displayName: "Emp Name",
        name: "empName"
      },
      {
        displayName: "Emp ID",
        name: "empId"
      },
      {
        displayName: "Salary",
        name: "salary"
      }
    ];
    this.rows = [
      {
        empId: "1",
        empName: "red",
        salary: "10000"
      },
      {
        empId: "1",
        empName: "red",
        salary: "50000"
      },
      {
        empId: "1",
        empName: "red",
        salary: "30000"
      }
    ];
  }
}

在版本 13 Angular 中,CLI 在新创建的项目上启用 TypeScript strict 模式。这会启用(除其他外)noImplicitAny 标志。

因为 header.name 可以是任何字符串,TypeScript 无法知道 row[header.name] 的类型,所以它将它分配给 any(并且正在抱怨)。

要解决此问题,您可以执行以下任一操作:

(1) 在您的 Row 接口上声明一个索引签名:

interface Row {
  [key: string]: string,
  empId: string,
  empName: string,
  salary: string
}

在这里您告诉 TS,通过字符串访问的 Row 上的任何 属性 都将具有 string 类型。

(2) 将 Header.name 的类型限制为 Row 的键的文字联合:

interface Header {
    displayName: string,
    name: keyof Row
}

在这里,您将 Header.name 的类型声明为 "empId" | "empName" | "salary"(不允许使用其他值)。

(3) 通过在 tsconfig.json 中设置 "noImplicitAny": false 禁用 noImplicitAny 标志(显然这将完全禁用检查)。