Skip to content

Type inferencing of filter style functions #1883

Open
@lewis6991

Description

@lewis6991

Given:

---@generic T
---@param f fun(a: T)
---@param t table<any, T>
---@return T[] (table)
local function tbl_filter(f, t)
  return t
end

---@type string[]
local s = {'a', 'b', 'c'}

local r1 = tbl_filter(function(a) end, s)

r1 is inferred as unknown[] because a is unknown despite s being known. However, could we infer a from s and force the typechecker to insist a is a string?

If I remove the type from a:

---@generic T
---@param f fun(a)
---@param t table<any, T>
---@return T[] (table)
local function tbl_filter2(f, t)
  return t
end

local r2 = tbl_filter2(function(_) end, s)

r2 is now inferred as string[] because only s is used to infer the type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestfeat/genericRelated to generic emulation feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions