Extending Shapes
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 41 of 73.
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
EasyCreate these type aliases:
Employee—id(number),name(string),department(string)Manager—Employeeextended (via&) withteamSize(number)Contact—email(string)Developer— the intersection ofEmployee,Contactand{yearsExperience: number}
Create:
teamLeadof typeManager— id101, name"Alice Johnson", department"Engineering", teamSize8devof typeDeveloper— id102, name"Bob Smith", department"Engineering", email"bob@company.com", yearsExperience5
Create a function getManagerSummary that takes a Manager and returns [name] manages [teamSize] people.
Print, each on its own line:
- the result of
getManagerSummary(teamLead) [name] has [yearsExperience] years of experiencefordev- the department of
teamLead - the email of
dev
Try it yourself
-- Write code here
-- 1) define Employee, then Manager / Contact / Developer with &
-- 2) create teamLead and dev
-- 3) write getManagerSummary
-- 4) print the four requested lines
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps