Menu
CoddyTech

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 icon

Challenge

Easy

Build a union out of two aliases and narrow it.

  1. Write type Username = string, type UserAge = number and type ContactMethod = Username | UserAge.
  2. Write local function getContactInfo(contact: ContactMethod): string: return `Contact: {contact}` for a string, otherwise `Age: {contact}`.
  3. Print getContactInfo("john_doe") and getContactInfo(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

Practice on your own: Online Luau compiler