type countryListProps = {
dial_code: string;
code: string;
name: string;
lower?: string;
};
const countryList: countryListProps[] = [
{
'dial_code': 'somevalue',
'code': 'somevalue',
'name': 'Somevalue',
},
{
'dial_code': 'somevalue',
'code': 'somevalue',
'name': 'Somevalue',
},
];
const toLower = {} as countryListProps[];
for (let i=0; i<countryList.length; i++) {
const country: countryListProps = countryList[i];
toLower[country.code] = country;
country.lower = country.name.toLowerCase(); // adding other propery 'lower'
}
打字稿给我:
元素隐式地具有“ any”类型,因为索引表达式不是“ number”类型。
我的目标只是添加'lower'作为类型为字符串的属性,因此每个对象的结果对象看起来都类似于:
{
'dial_code': '+756',
'code': 'something',
'name': 'UpperCase',
'lower': 'lowercase of name',
}
尝试将toLower
声明为:
const toLower: {[key: string]: countryListProps} = {};
您只使用
let newArr = countryList.map((i)=>{
return {
...i,
lower:'hello',
}
})
代替
const toLower = {} as countryListProps[];
for (let i=0; i<countryList.length; i++) {
const country: countryListProps = countryList[i];
toLower[country.code] = country;
country.lower = country.name.toLowerCase(); // adding other propery 'lower'
}