javascript - 编写带参数的函数,可用作对象属性
问题描述
interface item {
first: string;
last: string;
}
const arr = item[];
myfunc = (index, attributeToChange) => {
arr[index].attributeToChange = "New first/last"
}
在上面的代码中,我调用arr
了包含类型对象的数组item
。我正在尝试编写一个函数,该函数需要一个数组索引和一个字符串,该字符串attributeToChange
可以是first
or last
。
但是,如果我按照上面的方式编写函数(显然)会在 TypeScript 中的类型“item”错误中抛出 Property 'attributeToChange' does not exist on type 'item' error。
编写这样的函数的理想方法是什么?
解决方案
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;
}
推荐阅读
- r - 如何在ggplot中更改字体大小和颜色直接标签
- java - 如何将表格保存在数组中
- postgresql - 查询“SELECT text(textsend_i('一'));”时得到不同的结果 在 pgAdmin 和其他 PostgreSQL IDE 之间
- c++ - 使用 -O1 优化标志编译项目时共享库崩溃
- bash - 在开始新的子进程之前等待子进程完成
- shell - 如何从shell中的十六进制字符串获取反十六进制字符串
- string - 朱莉娅的独特对
- java - 我厌倦了用 JpaRepository 做一些事情但是找不到用 findById 的行,
- python - 如何根据数据帧的长度在数据帧中创建额外的列作为索引值
- jquery - 单击提交按钮时如何检查序列化数据是否为空