Type Checking Tables

Hi. I’ve checked out some threads and I can’t find my specific question anywhere. I have some custom-defined types of tables, and I’m wondering if there’s a way to specifically type check. For example… here are the defined types:

export type Object = {
    name: string,
    currentLevel: number,
    maxLevel: number,
    cost: number,
    cycleTime: number,
    timeRemaining: number,
    assetName: string,
    model: Model?,
}

export type InteractableObject = Object&{
    state: ObjectState,
    prompt: ProximityPrompt?
}

I want to be able to do something like:

if x:IsA("InteractableObject")

assuming that x is already known to be an object type. All interactable objects are objects but not all objects are interactable. I could check for a state property for this use case, but I’m just wondering for general purposes as well.

1 Like

The behavior you want isn’t currently possible in Luau

4 Likes

You should definitely check out the new Type Solver beta, with the new keywords maybe you can achieve your desired result.

2 Likes

Okay, reading it right now and there’s some good stuff. Appreciate it.

1 Like

Give a type literal string to each table then compare that value.

type t1 = {
  type: "cat"
}

type t2 = {
  type: "dog"
}

local function doThing(t: t1 | t2)
  if t.type == "cat" then
    -- infers as t1
  elseif t.type == "dog" then
    -- infers as t2
  end
end

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