luarobloxluau

How to define acceptable paramters in a export type as a range of numbers in Luau?


I'm currently mucking around with OOP in Luau. I wish to define the type of a property within Windfield called VisualMode to be in a range of numbers between 1-2 (not forcefully).

export type Windfield = {
Visualized: boolean,
VisualMode: 1|2
}

local module = {}
module.WindfieldClass={}
module.WindfieldClass.__index=module.WindfieldClass

function module.WindfieldClass.new()
    local self={}
    setmetatable(self,module.WindfieldClass)
    return self
 end


 return module

What is the correct syntax/method of implementation?


Solution

  • This is not possible. Luau does not support number literals as types (much less ranges - TypeScript for example, with a much more advanced type system, doesn't, unless you use rather complex and obscure string template literals). You'll have to conform with accepting a simple number. https://luau.org/typecheck#singleton-types-aka-literal-types

    If making sure only a set of acceptable values are valid types is necessary, you may want to use string literals or some other unique type.

    type VisualMode = "foo" | "bar"