How could I go about type checking for members of a table?
I’m asking because I made a very simple enums module for the sake of convenience and not misspelling things between scripts:
local Enums = {}
Enums.GameState = {
Intermission = "Intermission",
Voting = "Voting",
RoundPreparation = "RoundPreparation",
RoundInProgress = "RoundInProgress",
}
...
return Enums
While it autofills when being used in code, I don’t really have a type check for it when I’m using it as a function argument. It’s just a string
.
So when I have a function expecting a GameState
:
local function setGameState(newGameState : string)
-- do stuff
end
… the type checker only expects that newGameState
is a string, which is technically correct. But what I want is for the type checker to recognize that newGameState
must be a member of Enums.GameState
.
Now I know there’s a workaround (that I saw in a tweet somewhere):
By explicitly defining the type as a union of string literals, I get the result I’m looking for.
But that means I’ll have to make sure that the table and the type match whenever I make any changes.
I feel like that’s not the way to go about things just because it’s more maintenance needed for such a small thing, almost like there’s a smarter way to do it that I just don’t know.
I’ve read the Luau type checking page maybe 10 times now and I still can’t think of a way. I don’t even understand the type packs/generics thing, maybe that’s what I actually need.
Is there a more efficient way to do this? Or a more proper way? I know it’s not that important, I can live with it honestly, but it bugs me to no end. I’ve tried searching here in the forum but I haven’t found anyone with the same situation. Someone put me out of my misery.