Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically accessing object property in typescript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading