LuaLS / LuaLS/lua-language-server
Type narrowing for unioned classes
- Dominant language
- Lua
- Stars
- 4.4k
- Forks
- 442
- PR merge metrics
- No merged PRs in 30d
Description
I have a large number of classes that look something like this:
```lua
---@class Foo
---@field type "foo"
---@field name string
---@field property string
-- more unique fields
---@class Bar
---@field type "bar"
---@field name string
---@field stuff string
-- more unique fields
-- more classes
```
I have a function that takes an array of any of these classes as a parameter, so naturally I've unioned all of the classes.
```lua
---@alias Prototypes
---|Foo
---|Bar
-- all of the other classes
---@param prototypes Prototypes[]
local function extend(prototypes)
-- stuff and things
end
```
However, when I try to make `prototypes` a table literal, I get autocomplete for the other classes because the union operator behaves like intersection instead of union.

Is there any way to get it to show only the fields of the class indicated by the `type` field? I can't seem to find way to do a proper union of types.
`@type` seems to only work on variables, and even if it did work on table literals, it would be cumbersome to write out the type for every entry in the array.
Contributor guide
Research direction
Start by reproducing the annotated Foo/Bar Prototypes[] example from this issue and inspect the language server's union-type narrowing and table-literal completion behavior. Done means a discriminated union narrowed by the type field presents only the selected class fields in completion while preserving valid completion for other union members.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- lua
- Domain
- developer-experience, tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100