Define custom types for arrays for specific indices

In short, is this possible?

For example, this is what I want to do:

type SpecificArray = {
    [1]: string, -- The first index must be a string
    [2]: number, -- The second index must be a number
}

(but isn’t currently possible)

The following works but isn’t desired as I’d like to type check specific indices:

type NonSpecificArray = {string | number}

No, this isn’t possible because of how integers are treated. All integers fall under the generic type of number, and the Luau type checking engine doesn’t allow otherwise. You can, however, use other keys of the same type (such as strings) because they are treated differently by the type checker, almost as if they are their own type.

type Array = {
    [true]: "hi",
    ["hi"]: "bye"
}

when you say you want to type check specific indices, what do you mean by this? Do you mean statically check them pre-runtime, through something like a type function, or check them at runtime with functions like type and typeof?

1 Like

Yeah I also have this issue, I really want to define types like this, makes it easier to code but alas, gotta use dictionary…