Skip to content

Can't infer the return type of map #1153

Description

@skanev

Describe the bug

I'm writing a map function, but type inference doesn't work for it. Specifically, when you have map(list, fn) where fn is fun(item: A): B, the type inference cannot figure out what B is in the return type.

To Reproduce

Here's a snippet:

---@param n number
---@return string
local function as_string(n)
  return tostring(n)
end

---@generic A
---@generic B
---@param array A[]
---@param fn fun(item: A): B
---@return B[]
local function map(array, fn)
  local result = {}

  for _, item in ipairs(array) do
    table.insert(result, fn(item))
  end

  return result
end

---@type number[]
local numbers
numbers = { 1, 2, 3 }

-- expected to be string[], but is <B>[]
local strings = map(numbers, function(n) return as_string(n) end)

I'm using 3.2.3 in neovim, if that is relevant.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestfeat/LuaCats AnnotationsRelated to Lua Language Server Annotations (LuaCats)

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions