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)

It should be static.

It doesn’t, however, it got me thinking that maybe I could use normal dictionary with the possible values instead.

Like:

type fooArgs = {
    aNumber: number,
    aString: string,
    greeting: "hi",
    numberList: { number }
}

function foo(args: fooArgs)
    ...
end

Instead of just using the ...: number | string | { number } like @Ziffixture suggested

That’s your next best bet. If you’re trying to store data that has individual meanings, it is best you do it this way

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