Skip to content

Opaque Enums #2916

Answered by tomlau10
Nerixyz asked this question in Q&A
Oct 27, 2024 · 2 comments
Discussion options

You must be logged in to vote

I know a hacky way to do so:

---@meta

---@enum EventType
EventType = {
    Water = {}, ---@type EventType.Water
    Fire = {},  ---@type EventType.Fire
}

---@class WaterEvent
---@class FireEvent

--- Listen to some event
---@param ty EventType
---@param cb function
---@overload fun(ty: EventType.Water, cb: fun(event: WaterEvent))
---@overload fun(ty: EventType.Fire, cb: fun(event: FireEvent))
function listen(ty, cb) end
-- cb params can type narrow correctly
listen(EventType.Water, function(event) end)
listen(EventType.Fire, function(event) end)

-- all of below will throw `param-type-mismatch`
listen("Water", function(event) end)
listen("Fire", function(event) end)
listen("Wind", function

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by Nerixyz
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants