Ordered list Type Checking in Lua

Dose enyone know how to type check an ordered list? Something like this:

type orderedListTypeThing = {
  1: number
  2: string
  3: "hi"
  4: { number }
}

local cool: orderedListTypeThing = {69, "just a string.", "hi", { 4, 2, 0 }}
print(cool) -- epic B)

I would like to do this to try and add better type checking to the function foo(...: any) end thing. (don’t ask why… :fearful:)

1 Like

Is the ordered list going to be static, or is it going to be dynamic?

Assuming the positions of your elements are unchanging, no there is no way for you to achieve this. The best you can do is type an array that will contain your primitive types, but in no specific order. This is achieved through union typing:

type Example = {[number]: number | string | {number}}

Dunno if this helps but, you could do:

type orderedListTypeThing = {
  ["1"]: number?
  ["2"]: string?
  ["3"]: "hi"?
  ["4"]: { number }?
}

local function convert(t):orderedListTypeThing
    local ot = {} :: orderedListTypeThing 
    for i = 1, 4 do
        ot[toString(i)] = t[i]
    end
    return ot
end

local cool: orderedListTypeThing = convert({69, "just a string.", "hi", { 4, 2, 0 }})
print(cool) -- epic B)

Obviously it’s now a dictionary and you’d have to use stringified numbers to access the values, and table methods like insert and remove wouldn’t work consistently (but they would cause huge problems with the typing anyway if elements are shifting into different types)