[以编程方式添加对象时如何从对象数组中键入属性

问题描述 投票:0回答:2
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',
}
javascript typescript
2个回答
0
投票

尝试将toLower声明为:

const toLower: {[key: string]: countryListProps} = {};

0
投票

您只使用

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'
}
© www.soinside.com 2019 - 2024. All rights reserved.