interface ZoneI {
code: string;
name: string;
}
const dataList: ZoneI[] = [
{ code: 'C00', name: 'zone 00' },
{ code: 'C01', name: 'zone 01' },
{ code: 'C02', name: 'zone 02' },
{ code: 'C03', name: 'zone 03' }
]
findRow('code', 'C02')
function findRow(findRowBy: string, findRowValue: string) {
// findRowBy='code'; findRowValue='C02'
let row = dataList.find(c => c[findRowBy] === findRowValue)
}
错误:ts7053 lement implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ZoneI'. No index signature with a parameter of type 'string' was found on type 'ZoneI'.ts(7053)
答案 0 :(得分:0)
您需要告诉 ts 编译器 findRowBy
是 ZoneI
的键
function findRow(findRowBy: string, findRowValue: string) {
// findRowBy='code'; findRowValue='C02'
let key = findRowBy as keyof ZoneI;
let row = dataList.find(c => c[key] === findRowValue)
}
Here 是工作样本。