How to write a generic function that merges tables and keeps the type of all #1671
Unanswered
danielo515
asked this question in
Q&A
Replies: 4 comments 1 reply
-
This is what I tried so far: ---@generic T
---@generic A { [string]: T }
---@generic O { [string]: T }
---@param ... O|A
---@return O
function M.merge(...)
local sources = { ... }
local result = {}
for _, source in ipairs(sources) do
for key, value in pairs(source) do
result[key] = value
end
end
return result
end
|
Beta Was this translation helpful? Give feedback.
0 replies
-
Small attempts that didn't work ---Assigns the properties of one or more objects to another object
---@generic X
---@generic Y
---@generic A { [string]: X }
---@generic B { [string]: Y }
---@generic O { [string]: X | Y }
---@param a A
---@param b B
---@return O
function M.assign(a, b)end ---Assigns the properties of one or more objects to another object
---@generic X
---@generic Y
---@param a { [string]: X }
---@param b { [string]: Y }
---@return { [string]: X | Y } |
Beta Was this translation helpful? Give feedback.
0 replies
-
Any way of doing this? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Not fully supported yet, but you can try: ---@generic A, B
---@param a A
---@param b B
---@return A|B
local function merge(a, b)
end |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello.
I'm trying to write a generic function that is able to keep track of the properties of all the tables it merges. Currently I was not able to find a way, so I would love some help here.
Let me write the simplest example of what I want:
I want fooBar to have type
{a: boolean, b: boolean}
. Ideally I want the function to accept any number of tables to merge, but I will be fine if I have to write a set of fixed overloads to accept up to X table merges. Any hint will be greatly appreciated.Beta Was this translation helpful? Give feedback.
All reactions