Exporting a type without having write it twice

Hi, just asking for some help as I build my familiarity with Types.

Assume I have two modules:

Args:

--!strict

export type ArgumentOptions = "player" | "color" | "speed"
export type Argument = {
	description: string,
	parse: () -> (),
}

local Args:{[string]: Argument} = {
    ["player"] = {
        description = "",
        parse = function() end,
    },
    ["color"] = {
        description = "",
        parse = function() end,
    },
    ["speed"] = {
        description = "",
         parse = function() end,
    },
}

return Args

and Commands:

--!strict

local Args = require(script.Parent.Args)

type Command = {
	name: string,
	args: {Args.ArgumentOptions},
    run: () -> (),
}

local Commands:{Command} = {
    {
        name = "walkspeed",
        args = {"player", "speed"},
        run = function() end,
    },
    {
        name = "paint",
        args = {"player", "color"},
        run = function() end,
    },
}

return Commands

The goal is to have typechecking recommendations for Args when writing a command (so that it will recommend “player”, “color”, etc).

Is there a way to automatically build the ‘ArgumentOptions’ type from the keys within the Args dictionary so that I don’t have to write the argument twice every time I create a new one?

1 Like

You could use type inference by simply not defining the types, and letting Luau solve for - AKA infer - them for you. But I’d recommend manually defining them, because it forces your data structure to abide by those types.

1 Like

If you have the new type solver enabled, you can use the keyof type function

local Args = {
	["player"] = {
		description = "",
		parse = function() end,
	},
	["color"] = {
		description = "",
		parse = function() end,
	},
	["speed"] = {
		description = "",
		parse = function() end,
	},
}

export type ArgumentOptions = keyof<typeof(Args)>

1 Like

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