Question
How do I merge Luau type checking of a function newA
that returns a table of type tabA
with another function newB
that changes the table into a new type tabB
?
Problem
Currently I have a function newB
that tries to “inherit” the properties of function newA
that has the type tabA
. However, Luau says that I cannot write properties to the returned value since it is type tabA
.
Is there any method to combine the tables together without type checking giving an error?
--!strict
type tabA = {
Name: string,
Class: string
}
type tabB = tabA & {
Power: boolean,
Player: boolean
}
local function newA(): tabA
return {
Name = "GG",
Class = "Yes"
}
end
local function newB(): tabB
local tab = newA()
tab.Power = true -- Cannot add property 'Power' to table 'tabA'
tab.Player = false
return tab
end
print(newB())
Attempts
I’ve tried replacing the newB()
function with an iterator but this method is more expensive and Luau doesn’t realize that the Name
and Class
properties are being added, leading to the same error.
local function newB(): tabB
local tab = {
Power = true,
Player = false
}
for i, v in pairs(tabA()) do
tab[i] = v
end
return tab
end