Luau Merge Tables of Different Types?

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

You can set the interpreter to think it’s type tabB by using a 2 double colons :::

--!strict

type tabB = tabA & {
	Power: boolean,
	Player: boolean
}
-- code

local function newB(): tabB
	local tab = newA() :: tabB -- Now recognises this variable as "tabB"
	tab.Power = true
	tab.Player = false

	return tab
end

You can read this section (a very short section) from the Luau Syntax page:

3 Likes