You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中根据字符串键值更新对象?

在TypeScript中通过字符串键更新对象的实现方法

报错信息翻译

原报错信息翻译为:

类型为'<对象类型>'的对象上未找到带有类型为'number'的参数的索引签名

可行解决方案

1. 明确键的字符串类型

如果你的键变量被误推断为number类型,先将其转为字符串类型:

const user = { name: "Alice", age: 25 };
let key: unknown = "age";
// 转换为字符串类型
const strKey = key as string;
user[strKey] = 26;

2. 为对象添加字符串索引签名

若对象需要支持动态键,给对象类型定义字符串索引签名:

// 定义带字符串索引的类型,值类型按需调整
type DynamicObject = {
  [key: string]: string | number;
};

const user: DynamicObject = { name: "Alice", age: 25 };
const key = "age";
user[key] = 26;

3. 使用类型断言(已知键属于对象属性)

确定键是对象已有属性时,用keyof断言键的类型:

type User = { name: string; age: number };
const user: User = { name: "Alice", age: 25 };
const key = "age";
// 断言键为User的属性类型
(user[key as keyof User] as number) = 26;

4. 借助Record工具类型

用TypeScript内置的Record类型快速定义键值对结构:

const user: Record<string, string | number> = { name: "Alice", age: 25 };
const key = "age";
user[key] = 26;

内容的提问来源于stack exchange,提问作者lone-coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:05:55