Skip to content

Ipairs with genericΒ #2969

@ChouUn

Description

@ChouUn

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Windows

What is the issue affecting?

Annotations

Expected Behaviour

Should have got a correct type inference in a generic function.

Actual Behaviour

  1. could not specify a V-related type for result in the generic function
  2. ipairs will be inferred as unknown
  3. returns of the generic function will be inferred as a strange type

Reproduction steps

---@class Test
---@field name string

---@type Test[]
local tests = {
    { name = "test1" },
    { name = "test2" },
    { name = "test3" },
}

--[[
CORRECT:
    function group_by(rows: <V>[], key: string)
    -> table<string, <V>[]>
]]
---@generic V
---@param rows V[]
---@param key string
---@return table<string, V[]>
local function group_by(rows, key)
    --[[
        ---@type table<string, V[]>
        GOT: Undefined type or alias `V`.
    ]]
    local result = {}
    -- WRONG: local v: unknown
    for i, v in ipairs(rows) do
        local k = v[key]
        if not result[k] then
            result[k] = {}
        end
        table.insert(result[k], v)
    end
    return result
end

--[[
WRONG:
    local groups: table<string, <V>[]> | { [<K>]: Test }
EXPECTED:
    local groups: table<string, Test[]>
]]
local groups = group_by(tests, "name")

Additional Notes

No response

Log File

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions