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
EasyExtend an employee shape into a manager shape.
- Write
type Employee = {name: string, department: string}andtype Manager = Employee & {teamSize: number}. - Create
local teamLead: Manager = {name = "Alice Johnson", department = "Engineering", teamSize = 8}. - Print
`{teamLead.name} manages {teamLead.teamSize} people`, thenteamLead.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
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 ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe '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 TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler