Menu
Coddy logo textTech

Intersection Types

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

Unions say a value is one type or another. Intersection types point the other way: the ampersand & combines table shapes into a type that has all the fields of every part:

type HasName = { name: string }
type HasAge = { age: number }

type Person = HasName & HasAge

-- a Person must have BOTH fields
local user: Person = {
    name = "Alice",
    age = 25,
}

Leave out age and the checker complains — an intersection is an "and", never a pick-and-choose. This lets you build big shapes from small, reusable pieces: define focused types for separate concerns, then snap them together as needed:

type HasEmail = { email: string }

type Employee = HasName & HasAge & HasEmail

One important Luau note: intersect table shapes (and function types) — not primitives. Something like number & string is meaningless, since no value can be both at once. When you want "this shape plus that shape", & is your tool.

At runtime, of course, a Person is just a regular Lua table — the intersection exists only for the checker.

challenge icon

Challenge

Easy

Create two shape aliases: HasName with a name: string field, and HasAge with an age: number field.

Create Person as the intersection HasName & HasAge.

Create HasEmail with an email: string field, and Employee as the intersection of all three: HasName & HasAge & HasEmail.

Declare:

  • user: Person with name "Alice" and age 25
  • worker: Employee with name "Bob", age 30, and email "bob@company.com"

Create displayPerson(person: Person): string returning "Name: [name], Age: [age]", and displayEmployee(employee: Employee): string returning "Name: [name], Age: [age], Email: [email]".

Print displayPerson(user) and displayEmployee(worker) on separate lines.

Try it yourself

-- Write code here
-- type HasName = { name: string }, HasAge, HasEmail
-- type Person = HasName & HasAge
-- type Employee = HasName & HasAge & HasEmail
-- declare user and worker, write the two display functions,
-- print displayPerson(user) and displayEmployee(worker)
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