TypeScript / TypeScript Interfaces and Types

Understanding Intersection and Union Types

In this tutorial, we'll delve into intersection and union types in TypeScript, which allow us to create complex types that can hold different kinds of values.

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers defining and using interfaces and type aliases in TypeScript for object shapes and contracts.

Intersection and Union Types in TypeScript

Introduction

Brief Explanation of the Tutorial's Goal

In this tutorial, we will explore the concept of intersection and union types in TypeScript. These are powerful features that allow us to create complex types, which can hold different kinds of values.

What the User Will Learn

By the end of this tutorial, you will understand what intersection and union types are, how to use them, and where they can be beneficial in your TypeScript code.

Prerequisites

You should have a basic understanding of TypeScript and its type system. Familiarity with JavaScript will also be helpful.

Step-by-Step Guide

Intersection Types

Intersection types are a way of combining multiple types into one. This allows you to add together existing types to get a single type that has all the features you need.

Here's a basic example:

type First = { a: number; b: number; };
type Second = { b: string; c: string; };
type Combined = First & Second;

In this case, Combined is a type which has all the properties of First and Second types.

Union Types

Union types are about adding more types to a particular variable, allowing it to hold different types of values. Unlike intersection types, a variable with a union type can hold any one type of value from those specified in the union.

Here's a basic example:

type StringOrNumber = string | number;

In this case, a variable of type StringOrNumber can hold either a string or a number.

Code Examples

Intersection Types

type Employee = { name: string; };
type Manager = { employees: Employee[]; };
type CEO = Employee & Manager;

let ceo: CEO = {
    name: 'John',
    employees: [{ name: 'Jane' }, { name: 'Joe' }]
};

In this example, the CEO type is an intersection of Employee and Manager. Therefore, a CEO has both a name and employees.

Union Types

type StringOrNumber = string | number;

let input: StringOrNumber;

input = 'Hello'; // valid
input = 42; // valid
input = true; // Error: Type 'boolean' is not assignable to type 'StringOrNumber'

In this example, the input variable can be either a string or a number. Any other type would cause an error.

Summary

In this tutorial, we've learned about intersection and union types in TypeScript. Intersection types allow us to create a new type with properties from multiple other types, while union types allow a variable to hold a value of different types.

To continue learning, you might want to explore other advanced types in TypeScript like type guards, type aliases, and discriminated unions.

Practice Exercises

  1. Create an intersection type that combines two object types with different properties. Use this type to create an object that has properties from both types.

  2. Create a union type that can hold either a string, number, or boolean. Use this type to create a variable that can hold values of these types.

  3. Create a function that accepts a parameter of a union type you created. Inside the function, use type guards to determine the type of the parameter and perform different actions based on that.

Remember to practice and apply these concepts in real TypeScript projects to solidify your understanding. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help