解决typescript中无法使用对象作为获取对象属性的问题

错误现象

Error: src/app/routes/first/testmvvmtable/testmvvmtable.component.html:13:15 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ResourceVmRespData'.
No index signature with a parameter of type 'string' was found on type 'ResourceVmRespData'.

13 {{da[column]}}
~~~~~~~~~~

src/app/routes/first/testmvvmtable/testmvvmtable.component.ts:6:16
6 templateUrl: './testmvvmtable.component.html'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component TestmvvmtableComponent.

问题描述

在angular 13.3.9 + node 14.18.2 + alain 13 + npm 6.14.15 + yarn 1.22.19中

使用{{da[column]}}这样的语法获取对象属性时,出现了上面的问题;

<tr *ngFor="let da of basicTable.data">
<td *ngFor="let column of columnNameList;let i=index">
{{da[column]}}
</td>
</tr>

获取解决办法的博客

https://www.likecs.com/ask-1712144.html(解决办法五)

https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/(非html页面可以尝试的解决办法)

解决办法

为da对象添加一个父类(da为ResourceVmRespData)

interface IObjectKeys {
  [key: string]: string | number;
}

export interface ResourceVmRespData extends IObjectKeys{
  ip: string;
hosyIp: string;
adminIp: string;
hostSn: string;
env: string;
hostname: string;
groupName: string;
region: string;
idcName: string;
lifecycleName: string;
rackName: string;
state: string;
cpu: string;
disk: string;
memory: string;
mac: string;
}


posted @ 2022-08-24 16:47  哇塞咔咔  阅读(621)  评论(0)    收藏  举报