Menu
CoddyTech

Intersection Types

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 36 of 80.

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

Combine two small shapes into one.

  1. Write type HasName = {name: string}, type HasAge = {age: number} and type Person = HasName & HasAge.
  2. Create local user: Person = {name = "Omar", age = 31}.
  3. Print `Name: {user.name}, Age: {user.age}`.

Press Run Code: the output shows Name: Omar, Age: 31.

Try it yourself

-- 1) type HasName, type HasAge, type Person = HasName & HasAge
-- 2) local user: Person = {...}
-- 3) print the name and age line

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler