Luau Type Checking - Checking if an argument is an index of a table

Hello!

I’m wondering if three’s anyway to do a type check like how I’ve done on line 13 at Code: “111” | “222” but, instead of adding each index that’s inside of table to the type each time there is a new code added to the table, I’m wondering if three’s a way that it will automatically know weather its in the table or not and underline the code I’ve put.

local Codes = {
	["111"] = {
		Param1 = "145",
		Param2 = "525"
	},
	
	["222"] = {
		Param1 = "123",
		Param2 = "444"
	},
}

local function PrintSomething(Code: "111" | "222") --Line 13
	if Codes[Code] then
		print("Code: ", Code, "found inside of codes table")
	else
		print("Code: ", Code, "was not found inside of codes table")
	end
end

PrintSomething("111")
PrintSomething("333") --Underline 333 since its not found inside of the Codes table
PrintSomething("111")

The highlighted yellow, instead of “111” | “222”
it should be something like Code

image

Hopefully what I’ve said makes sense.

Thanks to anyone that can help!

1 Like

I believe to get what you want, you will have to make a type called “Code” and have the argument taken in be of type “Code”.

export type Code = "111" | "222"
function PrintSomething(code: Code) return end
1 Like

Is there a way to make it so it’ll automatically know? So I don’t have to add (| “RandomNumber”) everytime I add something new to the table?

1 Like