I am making a game in typescript. The game has an inventory system with several values like this:
export const Inventory = {
food: 0,
medicine: 0,
rifleAmmo: 0,
pistolAmmo: 0
}
Currently I am managing adding and subtracting from the Inventory with the following function
export const removeFromInventory = ({amount}: itemInterface) => {
return Inventory.rifleAmmo = Inventory.rifleAmmo - amount
}
I want to make this function accept a dynamic value for the name and the amount, currently I have this from other answers here on stackoverflow
enum itemType {
'rifle-ammo'
}
interface itemInterface {
amount: number,
item: itemType
}
export const AddToInventory = ({amount, item}: itemInterface) => {
return Inventory[item] = Inventory.item + amount
}
However I am getting the error that either a string cannot be used as an index type, having the type be "any" doesn’t help either. I know this is possible but my typescript skills are lacking.
How can I dynamically access an object’s property in typescript?
>Solution :
You could do it like this
type inventory = typeof Inventory;
export const Inventory = {
food: 0,
medicine: 0,
rifleAmmo: 0,
pistolAmmo: 0
}
enum itemType {
'rifle-ammo'
}
interface itemInterface {
amount: number,
item: keyof inventory
}
export const AddToInventory = ({amount, item}: itemInterface) => {
return Inventory[item] = Inventory[item] + amount
}