Type Checking Tables

I am trying to create a type that represents an inventory item, but some inventory items have more/different attributes than others. In the scope that I’m creating the type in, I only care that the inventory item has a Type and a Name attribute. How can I enforce this using type checking without running into errors when the item has more than those 2 attributes? This is my starting idea, but from my understanding this will create a “sealed” table that doesn’t allow additional attributes.

type InventoryItem = {
	Name: string,
	Type: string,
}

function signature:
function AddItemDataToCache(player: Player, item: InventoryItem)

You could try this:

type InventoryItem = {
	Name: string,
	Type: string,
    [string]: any
}
4 Likes

Couldn’t you just use type() on them?

--!strict

type InventoryItem = {
	Name: string,
	Type: string,
	[string]: { [string]: any }
}

local apple: InventoryItem = {
	Name = "Apple",
	Type = "Food",
	CustomAttributes = {
		Crunchy = true,
		HealthGain = 20
	}
}

This should work fine

table isn’t a valid class type. It has to be represented as [string]: {} or [string]: {[string]: any}.

1 Like

Thanks I’ve never actually used type checking myself so I wasn’t aware I’ll fix it now.

1 Like