TypeScript中如何动态访问对象属性?
解决TypeScript中动态访问对象属性的类型错误问题
针对你开发游戏背包系统时遇到的动态属性访问类型错误,下面是具体的修复方案:
问题根源
你的代码存在两个核心问题:
- 枚举
itemType的成员'rifle-ammo'和Inventory中的属性名rifleAmmo格式不匹配,导致索引无法对应 - 未正确约束
item参数的类型,使其与Inventory的键类型严格对齐
正确实现方案
利用TypeScript的keyof操作符自动推导Inventory的键类型,既避免手动维护枚举的不一致问题,又能保证类型安全:
- 定义类型约束
通过keyof typeof Inventory自动获取Inventory的所有属性名作为合法物品类型:
// 自动推导Inventory的键类型,无需手动维护枚举 type ItemType = keyof typeof Inventory; interface ItemInterface { amount: number; item: ItemType; }
- 修复增减物品函数
动态访问对象属性时直接使用Inventory[item],同时可增加边界检查(比如避免物品数量为负):
// 添加物品函数 export const addToInventory = ({ amount, item }: ItemInterface) => { if (amount < 0) throw new Error("添加数量不能为负数"); Inventory[item] += amount; return Inventory[item]; }; // 移除物品函数 export const removeFromInventory = ({ amount, item }: ItemInterface) => { if (amount < 0) throw new Error("移除数量不能为负数"); // 确保物品数量不会低于0 Inventory[item] = Math.max(0, Inventory[item] - amount); return Inventory[item]; };
- 完整代码示例
整合后的完整背包系统代码:
export const Inventory = { food: 0, medicine: 0, rifleAmmo: 0, pistolAmmo: 0 }; type ItemType = keyof typeof Inventory; interface ItemInterface { amount: number; item: ItemType; } export const addToInventory = ({ amount, item }: ItemInterface) => { if (amount < 0) throw new Error("添加数量不能为负数"); Inventory[item] += amount; return Inventory[item]; }; export const removeFromInventory = ({ amount, item }: ItemInterface) => { if (amount < 0) throw new Error("移除数量不能为负数"); Inventory[item] = Math.max(0, Inventory[item] - amount); return Inventory[item]; };
方案优势
keyof typeof Inventory会自动生成"food" | "medicine" | "rifleAmmo" | "pistolAmmo"联合类型,确保item参数只能是Inventory中存在的属性名- 动态访问
Inventory[item]时,TypeScript能确认该属性存在且类型为数字,不会再抛出"字符串无法用作索引类型"的错误 - 自动推导类型避免了手动维护枚举的麻烦,后续修改
Inventory的属性时,ItemType会自动更新,减少维护成本
内容的提问来源于stack exchange,提问作者Dylan Bozarth
相关产品推荐
相关产品推荐

