Hello, I have a question about the Luau type check system. I created a function to merge two tables together and the returned table’s type is an intersection of the two argument tables
function TableUtils.Merge<T, U>(TableA: T, TableB: U): T & U
-- Code to merge tables
end
local A = {
ValueA = 10
}
local B = {
ValueB = 20
}
local C = TableUtils.Merge(A, B) -- Intellisense will show C.ValueA and C.ValueB
This worked fine, but now I want to create a merge function that allows for any amount of tables to be passed in. This is the best I could come up with but I can’t figure out how to intersect the returning type.
function TableUtils.Merge<T...>(...: T...): T...
-- Code to merge tables
end
Intellisense seems to only show the first table’s values in the returned table instead of all of them. Does anyone know how I can change TableUtils.Merge to accept any amount of tables and have the returned table be an intersection of all the passed arguments?
Currently it’s not 100% possible to have dynamic function return types (I say not 100% possible because there are cases like this). I’m pretty sure the built-in functions that have this functionality have it hardcoded.
I also came across this, which further explains this topic.
I believe ...T expects all arguments to be the same type and not T.... From Type checking - Luau, there’s an excerpt that talks about it.
Keep in mind that ...T is a variadic type pack (many elements of the same type T ), while U... is a generic type pack that can contain zero or more types and they don’t have to be the same.
That first link you posted has given me an idea though. I suppose I could just hardcode the types and have any arguments past the first two be optional.
function TableUtils.Merge<T,U,V,W>(TableA: T, TableB:U, TableC: V?, TableD: W?): T & U & V & W
-- Code to merge tables
end
It’s way more verbose than I would’ve ideally liked but eh, it works I guess lol. In any case, thanks for looking into this and posting the links