LuaLS / LuaLS/lua-language-server

Type narrowing for unioned classes

未关闭
#2,109 2 条评论 6 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

enhancement
主要语言
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.

![image](https://github.com/LuaLS/lua-language-server/assets/88168191/6ec8340a-2921-4a5d-b781-5f36094b8bdb)

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.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先复现此 issue 中带注解的 Foo/Bar Prototypes[] 示例,并检查 language server 的联合类型收窄和表字面量补全行为。完成的标准是:按 type 字段收窄后的可区分联合类型在补全中只显示所选类的字段,同时保留对其他联合成员的有效补全。

由索引模型根据 Issue 内容生成。

评估

技术栈
lua
领域
developer-experience, tooling
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。