Menu
CoddyTech

Extending Shapes

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

Related shapes often share fields. Every Admin is also a User; copying the shared fields into both declarations invites them to drift apart.

You met the intersection operator & when combining aliases. It works exactly the same for shapes. A & B means "has everything from A and everything from B":

type User = {name: string, age: number}
type Admin = User & {level: number}

-- Admin now requires: name, age AND level
local root: Admin = {name = "Root", age = 35, level = 9}

Where TypeScript needs a separate extends keyword for interfaces, Luau needs nothing new: intersections already do the job. You can chain several parts:

type Contact = {email: string}
type Developer = User & Contact & {yearsExperience: number}

Don't confuse & with |: a union A | B is either shape, while an intersection A & B must satisfy both at once. And since Admin has every User field, an Admin value can be passed anywhere a User is expected.

challenge icon

Challenge

Easy

Extend an employee shape into a manager shape.

  1. Write type Employee = {name: string, department: string} and type Manager = Employee & {teamSize: number}.
  2. Create local teamLead: Manager = {name = "Alice Johnson", department = "Engineering", teamSize = 8}.
  3. Print `{teamLead.name} manages {teamLead.teamSize} people`, then teamLead.department.

Press Run Code: the output shows Alice Johnson manages 8 people and Engineering.

Try it yourself

-- 1) type Employee, then type Manager = Employee & {...}
-- 2) local teamLead: Manager = {...}
-- 3) print the summary line, then the department

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler