LuaLS / LuaLS/lua-language-server
Type narrowing for unioned classes
还没有人认领这个 Issue。
- 主要语言
- Lua
- 星标
- 4.4k
- 派生
- 442
- PR 合并指标
- 30 天内没有已合并 PR
描述
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.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先复现此 issue 中带注解的 Foo/Bar Prototypes[] 示例,并检查 language server 的联合类型收窄和表字面量补全行为。完成的标准是:按 type 字段收窄后的可区分联合类型在补全中只显示所选类的字段,同时保留对其他联合成员的有效补全。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- lua
- 领域
- developer-experience, tooling
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100