Combining Type Aliases
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 37 of 80.
You now have all the pieces: aliases, unions, intersections, shapes, literals. The real power appears when they reference each other. Aliases can be built from other aliases, layer by layer:
type Username = string
type UserAge = number
-- a union of two aliases
type ContactMethod = Username | UserAge
-- a shape whose fields use the aliases above
type UserProfile = {
id: number,
displayName: Username,
preferredContact: ContactMethod,
}
-- an intersection extending the shape
type AdminProfile = UserProfile & { permissions: string }Every layer stays readable: displayName: Username says far more than displayName: string, and AdminProfile is visibly "a UserProfile plus permissions". Update a base alias once, and every composed type inherits the change automatically.
Literal unions compose the same way:
type Theme = "light" | "dark"
type Mode = Theme | "auto" -- "light" | "dark" | "auto"Remember the alias is transparent: ContactMethod is still string | number underneath, so working with one means the same typeof narrowing you already know.
Challenge
EasyBuild a union out of two aliases and narrow it.
- Write
type Username = string,type UserAge = numberandtype ContactMethod = Username | UserAge. - Write
local function getContactInfo(contact: ContactMethod): string: return`Contact: {contact}`for a string, otherwise`Age: {contact}`. - Print
getContactInfo("john_doe")andgetContactInfo(25).
Press Run Code: the output shows Contact: john_doe and Age: 25.
Try it yourself
-- 1) type Username, type UserAge, type ContactMethod = Username | UserAge
-- 2) getContactInfo(contact: ContactMethod): string, narrowing with typeof
-- 3) print it for "john_doe" and 25
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler