TS7053。隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'ZoneI'

时间:2021-07-11 14:13:58

标签: typescript

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)

1 个答案:

答案 0 :(得分:0)

您需要告诉 ts 编译器 findRowByZoneI 的键

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 是工作样本。