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
EasyCombine two small shapes into one.
- Write
type HasName = {name: string},type HasAge = {age: number}andtype Person = HasName & HasAge. - Create
local user: Person = {name = "Omar", age = 31}. - 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
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