首页 > 解决方案 > 编写带参数的函数,可用作对象属性

问题描述

interface item {
  first: string;
  last: string;
}

const arr = item[];

myfunc = (index, attributeToChange) => {
  arr[index].attributeToChange = "New first/last"
}

在上面的代码中,我调用arr了包含类型对象的数组item。我正在尝试编写一个函数,该函数需要一个数组索引和一个字符串,该字符串attributeToChange可以是firstor last

但是,如果我按照上面的方式编写函数(显然)会在 TypeScript 中的类型“item”错误中抛出 Property 'attributeToChange' does not exist on type 'item' error。

编写这样的函数的理想方法是什么?

标签: javascripttypescript

解决方案


attributeToChange您必须以类似的值查找属性index

arr[index][attributeToChange] = "New first/last"

您还需要将类型注释移动到左侧:

const arr: item[] = [];


编辑:根据您说 TypeScript 编译器告诉您的评论[ts] Element implicitly has an 'any' type because type 'item' has no index signature.,您需要向界面添加索引签名。通过指定其中的键类型和值类型item,它不会警告您有任何类型。

interface item {
  [key: string]: string;
  first: string;
  last: string;
}

推荐阅读