有一个API可以返回这种json:
{
id: '1'
, name: 'name1'
, ingredient1: 'ingredient1'
, ingredient2: 'ingredient2'
, ingredient3: ''
}
当循环遍历上面的 json 数组的响应时,我想选取所有成分并将它们放入一个数组中。但打字稿不太喜欢我这样做的方式并显示错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DrinkResponseType'. No index signature with a parameter of type 'string' was found on type 'DrinkResponseType'.
export type DrinkResponseType = {
id: string;
name: string;
ingredient1: string;
ingredient2: string;
ingredient3: string;
}
const drinks: Array<DrinkResponseType> = response.drinks;
drinks.forEach((item: DrinkResponseType) => {
let all_ingredients: Array<string> = [];
for(let i=1;i<=3;i++){
const label = `ingredient1${i}`;
const value = item[label];
if(value){
all_ingredients.push(value);
}
}
console.log(all_ingredients);
})
如果我在标签声明之前添加 // @ts-ignore,我就可以让它工作。 但看起来仍然应该有更好的方法来避免这个错误。
问题在于您的 fori 循环无法在编译时解析循环的边界。您可以通过迭代 const 数组来解决此问题,请参阅 this Playground 链接
type DrinkResponse = {
id: string;
name: string;
ingredient1: string;
ingredient2: string;
ingredient3: string;
}
declare const drinks: DrinkResponse[];
for (const drink of drinks) {
const ingredients: string[] = []
for (const i of [1, 2, 3] as const) {
const key = `ingredient${i}` as const
const value = drink[key]
if (value) {
ingredients.push(value)
}
}
}