Intersection Types ('&')
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 34 of 73.
While union types let you create variables that can be one of several types, intersection types work in the opposite direction. They combine multiple types into a single type that has all the properties of the combined types.
Intersection types use the ampersand (&) operator to merge types together. When you intersect two object types, the result contains every property from both types:
type HasName = { name: string };
type HasAge = { age: number };
type Person = HasName & HasAge;
// Person now has both name AND age properties
let user: Person = {
name: "Alice",
age: 30
};This is particularly useful when you want to build complex types from smaller, reusable pieces. Instead of defining one large object type, you can create focused types for specific concerns and then combine them as needed.
Intersection types ensure that the resulting type satisfies all the requirements of the intersected types. The variable must have every property from every type in the intersection - there's no picking and choosing like with unions.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate two type aliases: HasName for an object with a name property of type string, and HasAge for an object with an age property of type number.
Create a third type alias called Person by intersecting HasName and HasAge using the & operator.
Create another type alias called HasEmail for an object with an email property of type string.
Create a fourth type alias called Employee by intersecting all three types: HasName, HasAge, and HasEmail.
Now create the following variables:
- Create a variable named
userof typePersonwith the name"Alice"and age25 - Create a variable named
workerof typeEmployeewith the name"Bob", age30, and email"bob@company.com"
Create a function named displayPerson that accepts a parameter of type Person and returns a string in the format "Name: [name], Age: [age]".
Create another function named displayEmployee that accepts a parameter of type Employee and returns a string in the format "Name: [name], Age: [age], Email: [email]".
Call both functions with the appropriate variables and print the results on separate lines.
Cheat sheet
Intersection types combine multiple types into a single type that has all the properties of the combined types using the ampersand (&) operator:
type HasName = { name: string };
type HasAge = { age: number };
type Person = HasName & HasAge;
// Person now has both name AND age properties
let user: Person = {
name: "Alice",
age: 30
};The resulting type must satisfy all requirements of the intersected types - every property from every type in the intersection is required.
Try it yourself
// TODO: Write your code here
// Create type aliases for HasName, HasAge, HasEmail
// Create Person and Employee types using intersection
// Create variables user and worker
// Create displayPerson and displayEmployee functions
// Call the functions and print the resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples