How to make a type. How to make a type that describes any think

My friend asked me the question “How to make a type that describes a table?”. I don’t understand what that means at all! :sob:

I think they mean create a type that defines the element of a table. Type declaration in Luau is done by a colon. So, to declare a variable as a table of strings:

local variable: {string} = {"This is a table of strings", "another string here"}

To declare a variable as a dictionary of strings to strings:

local variable: {string: string} = {
    ["Entry"] = "Table of strings to strings"
}

Obviously, this can get a bit annoying with larger data sets. You can make a variable to hold this type.

type MyType = {
    ["Something"]: number, --something is the key and a number is associated with it
    [any]: {string}, --this entry takes anything for the key and holds a table of strings
    ["Method"]: (MyType) -> (boolean, number) --Method is a function that takes MyType as a parameter and returns a boolean and a number
}

We can stick export in front of this within modules to make it accessible from outside of them.

export type MyType = {
    ["Something"]: number, --something is the key and a number is associated with it
    [any]: {string}, --this entry takes anything for the key and holds a table of strings
    ["Method"]: (MyType) -> (boolean, number) --Method is a function that takes MyType as a parameter and returns a boolean and a number
}

then:

local module = require(path_to_module_here)
local myData: module.MyType = {
    ["Something"] = 1,
    [workspace:FindFirstChildOfClass("Part")] = {"SomethingRandom"},
    ["Method"] = function(someParameter: module.MyType): (boolean, string)
        --blah blah stuff here
        return true, 5
    end
}
1 Like

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