lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

Support discriminated unions / type narrowing

Open grapereader opened this issue 3 years ago • 4 comments

In TypeScript this is supported by "narrowing"

Consider this example:

---@alias ChatAction { type: '"chat"', targetName: string, msg: string }
---@alias NotifyAction { type: '"notify"', msg: string, colour: number }
---@alias ActionType ChatAction | NotifyAction

---@param action ActionType
local function example(action)
    -- action is any action (properties 'type', 'msg')
    if (action.type == 'chat') then
        -- action is ChatAction (properties 'type', 'msg', 'targetName')
    end
    if (action.type == 'notify') then
        -- action is NotifyAction (properties 'type', 'msg', 'colour')
    end
end

For a union type such as 'ActionType' in the example, the only defined properties should be those common to all types. After narrowing (through some sort of type check, in this case a type field) the additional properties in the narrowed subset are also available.

grapereader avatar Oct 03 '21 00:10 grapereader