LuaLS / LuaLS/lua-language-server

[Feature Request] Intersection types

未关闭
#3,152 3 条评论 4 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Lua
星标
4.4k
派生
442
PR 合并指标
30 天内没有已合并 PR

描述

I apologize if this request has been reported before, I couldn't find any.
It would be great to be able to explicitly differentiate between union types and intersection types
e.g.
```lua
--- @class A
local a = {foo = 1}

--- @class B
local b = {bar = "hello"}

--- @param aOrB A | B
--- @param aAndB A & B
local function someFunc(aOrB, aAndB) end

someFunc(a, a) -- no warning, but 2nd argument should give a warning

--- @param a A
local function someOtherFunc(a) end

--- @type A | B -- would prefer to use A & B and not have any warnings
local aAndB = {foo = 1, bar = "hello"}
someOtherFunc(aAndB) -- Cannot assign `A|B` to parameter `A`. - `B` cannot match `A` - Type `B` cannot match `A` Lua Diagnostics. (param-type-mismatch)
```

While it's possible to use an explicit class with inheritance as a workaround, this is not always viable, especially when using dynamic types with generics
```lua
--- @class C: A, B
local c = {foo = 1, bar = "hello"}
someOtherFunc(aAndB) -- no warning

-- not viable when using something like this
--- @generic T1, T2
--- @param tbl1 T1
--- @param tbl2 T2
--- @return T1 | T2 -- would like to use T1 & T2 instead to avoid the warnings
local function merge(tbl1, tbl2) end

someOtherFunc(merge(a, b)) -- Cannot assign `A|B` to parameter `A`. - `B` cannot match `A` - Type `B` cannot match `A` Lua Diagnostics. (param-type-mismatch)
```

The suggested syntax `A & B` for intersection types and `A | B` for union types matches several other languages, such as TypeScript and PHP.

Edit: another workaround is to enable [luals.github.io/wiki/settings#typeweakunioncheck](https://luals.github.io/wiki/settings/#typeweakunioncheck). This has its own downsides, but may be helpful for people trying to avoid the `param-type-mismatch` warnings

贡献指南

打开贡献指南

从这里开始

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

调研方向

未指定实现文件或测试。首先跟踪 Lua 注解如何表示联合类型,以及 param-type-mismatch 诊断如何处理它们,然后将行为与 A & B、A | B 和泛型合并示例进行比较;当交集注解避免所示的误报,同时联合类型保留当前检查时,即表示完成。

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

评估

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

把新 issue 发到你的邮箱

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