Any way to map keys from table with type checker?

I am trying to get the autocompleter to be useful. I have a dictionary of item data. For each item there will be a table in the players profile that saves data like quantity.

I want to create a type that contains all the keys from the item dictionary, but the type of each key is custom instead of inferred.

Example:

-- Generic Items Dictionary
local items = {
    Apple = {
        health = 5,
        price = 5
    },
    Banana = {
         health = 10,
         price = 10
    },
    Cucumber = {
         health = 20,
         price = 20
    }
}

local profile = PlayerProfiles.GetProfile(player)

-- I want the type profile.Data to be
type itemSave = {
   Apple: {quantity: number},
   Banana: {quantity: number},
   Cucumber: {quantity: number}
}

The goal is to get autocomplete to be able to fill out this line on it’s own.

profile.Data.Apple.quantity

Obviously I don’t want to manually make the type and add every item to it because then I have to remember to keep the item type in sync with the item table whenever I change the table and that breaks single source of truth.

Unfortunately you would have to statically type it out (or write a script that generates it for you), or just assume every string key is that data value.

type itemSave = {
    [string]: {quantity: number}
    -- you can still add each one individially
}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.