lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

[feat] generics: capture types with backticks

Open jpeletier opened this issue 6 months ago • 10 comments

This PR modifies the generics capture system to allow to capture types out of the type of the parameter passed, in addition to being able to pass the type as a string which is the way it currently works:

Currently:

---@class Vehicle
local Vehicle = {}

---@class VehicleColor
local VehicleColor = {}

---@generic T
---@param class `T`Color # the type is captured using `T`
---@return T       # T becomes class + "Color"
local function getItemColor(class) end

-- obj: is of type VehicleColor
local obj = getItemColor("Vehicle")

Now, the following is also possible:

---@class Vehicle
local Vehicle = {}

---@class VehicleColor
local VehicleColor = {}

---@generic T
---@param class `T`Color # the type is captured using `T`
---@return T       # T becomes typeof(class) + "Color"
local function getItemColor(class) end

---@type Vehicle
local someVehicle = {}

-- obj: is of type VehicleColor
local obj = getItemColor(someVehicle)

-- obj2: is of type VehicleColor
local obj2 = getItemColor("Vehicle")

Therefore, it is possible to pass a literal string that happens to be a type name like before, or otherwise pass an expression that evaluates to a type and that type will be captured with backticks. This allows to construct typings for functions that return different types that depend on the type of the object passed.

jpeletier avatar Apr 04 '25 09:04 jpeletier