【问题标题】:Add type annotations to Lua function that merges two tables and make the LSP track the keys为合并两个表的 Lua 函数添​​加类型注释并使 LSP 跟踪键
【发布时间】:2022-12-17 01:02:27
【问题描述】:

我正在尝试使用泛型键入一个 Lua 函数,以便 Lsp(在本例中为 sumneko-lua)能够跟踪所有涉及的表的属性。目前我找不到办法,所以我很想在这里得到一些帮助。

让我写下我想要的最简单的例子:

local foo = { a = true }
local bar = { b = true }
-- merge is the function I'm trying to type
local fooBar = merge(foo, bar)

我希望 fooBar 的类型为 {a: boolean, b: boolean}。理想情况下,我希望该函数接受任意数量的表进行合并,但如果我必须编写一组固定重载来接受最多 X 个表合并,我会很好。

我尝试过但没有用的一些东西是:


---@generic T
---@generic A { [string]: T }
---@generic O { [string]: T }
---@param ... O|A
---@return O
function M.merge(...)

---Assigns the properties of one or more objects to another object
---@generic X
---@generic Y
---@generic A { [string]: X }
---@generic B { [string]: Y }
---@generic O { [string]: X | Y }
---@param a A
---@param b B
---@return O
function M.merge(a, b)

【问题讨论】:

    标签: generics lua


    【解决方案1】:

    这些天我也在摸索sumneko_lua。

    尝试不同的方法,我想出了一个解决方案,可以用固定数量的参数解决问题:

    ---@generic T1 : table
    ---@generic T2 : table
    ---@param a T1
    ---@param b T2
    ---@return T1 | T2
    local function merge(a, b) end
    
    local foo = { a = true }
    local bar = { b = "true" }
    
    --[[ local fooBar: {
        a: boolean = true,
        b: string = "true",
    } ]]
    local fooBar = merge(bar, foo)
    

    有趣的是,该解决方案在嵌套调用时有效。 因此,您将能够:

    local foo = { a = true }
    local bar = { b = "true" }
    local baz = { c = 1 }
    
    --[[ local fooBarBaz: {
        a: boolean = true,
        b: string = "true",
        c: integer = 1,
    } ]]
    local fooBarBaz = merge(merge(foo, bar), baz)
    

    相反,我无法让它使用可变数量的参数,因为语言服务器似乎将第一个参数的推断类型应用于所有参数。

    您可以在 language server wiki 中找到所有支持的注解

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      相关资源
      最近更新 更多