-
Here is a small snip of code for context: ---@class Human
---@field name string
---@field age integer
local Human = {}
Human.name = "Charles"
Human.age = 30
---@generic T
---@generic Obj : `T`
---@param type T
---@param overrides Obj
function Make(type, overrides)
local new = {}
for k, v in pairs(type) do
new[k] = overrides[k] or v
end
return new
end
Make(Human, {age = 50}) I want to make It's not a huge issue if not possible, but would be great QoL for a library im working on. ---@generic T
---@generic Obj : `T`
---@param type T
---@param overrides Obj
function Make(type, overrides) Signature does not work and neither does ---@generic T
---@param type T
---@param overrides T
function Make(type, overrides) Any help would be appreciated thank you for your time. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This seems to me impossible 😕 because when you specify a param with a generic type To achieve this, what I can come up with is to modify the
---@class Human
---@field name string
---@field age integer
local Human = {}
Human.name = "Charles"
Human.age = 30
local factories = {}
---@generic T
---@param type T
---@return fun(obj: T): T
function MakeFactory(type)
local factory = factories[type]
if factory == nil then
factory = function (overrides)
local new = {}
for k, v in pairs(type) do
new[k] = overrides[k] or v
end
return new
end
factories[type] = factory
end
return factory
end
-- then you can have the following syntax
MakeFactory(Human) {
age = 50,
--[[ field auto completion here ]]
}
-- or even use a local var for the factory function
local MakeHuman = MakeFactory(Human)
MakeHuman({ age = 50, --[[ auto completion here ]] }) |
Beta Was this translation helpful? Give feedback.
This seems to me impossible 😕 because when you specify a param with a generic type
T
, you are capturing its type, not enforcing its type. In order to have autocompletion for theoverrides
object, you must first specify the actual type of it in the function param, not generic type.To achieve this, what I can come up with is to modify the
Make()
syntax:MakeFactory(type)
=> return a closure function that accepts a param of typetype