Skip to content

Support discriminated unions / type narrowing #704

Open
@grapereader

Description

@grapereader

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions