How do I make a type that accepts an array of other types?

The title is pretty self explanatory but to elaborate further, I wanted to make a Tab system. The user can basically cycle through various categories via clicking a button. I wanted to incorporate type checking into this system. My idea was to create a Tab type that holds information about each tab, such as the name of the tab and what content should be displayed. And another type that simply holds any number of Tab types. But im not exactly sure how to accomplish this.

Below is the code I assumed would do this but I get the dreaded red underline so clearly the syntax isn’t this.

type Tab = {tabName: string}
type Tabs = {...: Tab}

-- Ideally, Id like to do the following shown below, but as stated, the lines above cause red underlines:
local myTab: Tab = {tabName = "Tab1"} -- Create tabs
local myTab2: Tab = {tabName = "Tab2"}
local myTab3: Tab = {tabName = "Tab3"}

local myTabs: Tabs = {myTab, myTab2, myTab3} -- store tabs in a Tabs type, that accepts and inf number of Tab types

Image for further reference
RobloxStudioBeta_wGVCH5fbjd

1 Like

This should work (array types):

type Tabs = {Tab}
2 Likes

luau cant directly specify a type that accepts an array of other types like you would in other statically typed languages. But with a function you can do something similar.

-- initialize
type Tab = {
	tabName: string
}

-- function to check if all stuff in a table are tab sype
local function isArrayOfTabs(tabs: {Tab}): boolean
	for _, tab in ipairs(tabs) do
		if type(tab) ~= "table" or type(tab.tabName) ~= "string" then
			return false
		end
	end
	return true
end

-- define tab
local myTab: Tab = {tabName = "Tab1"}
local myTab2: Tab = {tabName = "Tab2"}
local myTab3: Tab = {tabName = "Tab3"}

-- store tab
local myTabs = {myTab, myTab2, myTab3}

-- check if mytabs is an array of tab types
if isArrayOfTabs(myTabs) then
	print("myTabs is an array of Tab types")
else
	print("myTabs contains elements that are not of type Tab")
end

1 Like

I appreciate both replies, but @fellow_meerkat’s method actually works so there’s no need for the function method you proposed.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.