Menu
Coddy logo textTech

Combining Type Aliases

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 35 of 73.

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 icon

Challenge

Easy

Create the following aliases, each built on the previous ones:

  • Username = string
  • UserAge = number
  • ContactMethod = Username | UserAge
  • UserProfile = a shape with id: number, displayName: Username, preferredContact: ContactMethod
  • AdminProfile = UserProfile & { permissions: string }

Declare:

  • regularUser: UserProfile — id 1, displayName "john_doe", preferredContact "john_doe"
  • systemAdmin: AdminProfile — id 2, displayName "admin", preferredContact 25, permissions "full_access"

Create getContactInfo(contact: ContactMethod): string — narrow with typeof: for a string return "Contact: [contact]", for a number return "Age: [contact]".

Print, each on its own line:

  1. getContactInfo(regularUser.preferredContact)
  2. getContactInfo(systemAdmin.preferredContact)
  3. systemAdmin.permissions

Try it yourself

-- Write code here
-- type Username = string, UserAge = number
-- type ContactMethod = Username | UserAge
-- type UserProfile = { id, displayName, preferredContact }
-- type AdminProfile = UserProfile & { permissions: string }
-- declare regularUser and systemAdmin
-- getContactInfo narrows with typeof, then print the three lines
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau