If you want to constrain a TypeScript function input to specific values, you must define those values at the type level using "literal" types. These types only accept particular values, allowing you to create restrictions by combining these literal types as unions.
Within TypeScript, primitive literal types exist for strings like "hello"
, numbers like 123
, boolean values like true
, and special types such as null
and undefined
. Additionally, there are unique symbols and enums for numeric and string literals.
Unfortunately, TypeScript lacks literal object types, preventing the definition of specific objects as distinct types. Using generics can provide a solution by making properties generic, enabling distinctions between approved values at the type level.
An alternative method is to utilize literal types like string enums to designate approved objects through key-value mappings. By leveraging an enum akin to Direction
, you can map each direction to its associated coordinates and ensure that the move()
function accepts only these predefined values.
Ultimately, depending on your requirements, you can adopt either approach to restrict function inputs based on specific values in TypeScript.