Combining Types and Using Type Guards

Learn the differences between unions and intersections, how to use type assertions correctly, and common type guard techniques in TypeScript.

🎯 Introduction

This article teaches you how to use union and intersection types, apply type assertions, and distinguish types with typeof, instanceof, and custom type guards. You will also learn how literal types help you write safer, more effective frontend code.


🔀 Union Types and Intersection Types

First, let us distinguish these two types. Their names sound similar, but they serve different purposes.

A union uses | to specify that a value can have one of several types. For example, a variable might hold either a string or a number.

An intersection uses & to require a value to satisfy multiple types at once, combining their requirements.

Union Type Example

type ID = number | string;

function printId(id: ID) {
    console.log('Your ID is: ' + id);
}

printId(123);
printId('abc123');

The id parameter accepts either a number or a string. Either type is valid, as long as it is one of those two.

Intersection Type Example

interface Person {
    name: string;
    age: number;
}

interface Employee {
    employeeId: number;
}

type EmployeePerson = Person & Employee;

const emp: EmployeePerson = {
    name: 'Sam',
    age: 30,
    employeeId: 101,
};

EmployeePerson must have the properties required by both Person and Employee.

Intersection types commonly combine object types to describe objects with multiple responsibilities. Union types are useful when a function parameter can accept several different types.

✨ Type Assertions (as)

A type assertion tells the compiler that you have more specific information about a value's type: “I know what type this value has.”

Basic Usage

let someValue: unknown = 'This is a string';

let strLength: number = (someValue as string).length;

someValue has type unknown. The assertion as string tells the compiler to treat it as a string, allowing access to its length property.

A type assertion does not convert a value. It only tells the compiler to trust your type information. An incorrect assertion can lead to runtime errors.

🔍 Type Guards

Type guards narrow types, such as members of a union, so you can safely access properties and methods specific to a type.

typeof Type Guards

typeof distinguishes primitive types such as "string", "number", and "boolean".

function double(value: number | string) {
    if (typeof value === 'string') {
        return value.repeat(2);
    } else {
        return value * 2;
    }
}

This code uses typeof to determine whether the value is a string or a number, then performs the appropriate operation.

instanceof Type Guards

instanceof checks whether an object is an instance of a class or constructor.

class Dog {
    bark() {
        console.log('Woof');
    }
}

class Cat {
    meow() {
        console.log('Meow');
    }
}

function speak(animal: Dog | Cat) {
    if (animal instanceof Dog) {
        animal.bark();
    } else {
        animal.meow();
    }
}

Custom Type Guards

Sometimes you need a guard function with a type predicate as its return type: param is Type.

interface Fish {
    swim: () => void;
}

interface Bird {
    fly: () => void;
}

function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
    if (isFish(pet)) {
        pet.swim();
    } else {
        pet.fly();
    }
}
Type guards help make code safer and prevent runtime errors. Used appropriately, they also make the logic clearer and easier to maintain.

🏷️ Literal Types

A literal type restricts a value to a specific literal, such as "left" or "right".

Example Use Case

type Direction = 'left' | 'right' | 'up' | 'down';

function move(direction: Direction) {
    console.log('Direction: ' + direction);
}

move('left'); // Valid
// move("forward"); // Error: compilation fails

This limits the argument to the listed directions and prevents invalid values.

Literal types improve type safety and make code more self-explanatory.
Use literal types to restrict parameters when designing components or functions.

❓ Questions and Answers

Q1: What is the key difference between unions and intersections?

A union allows a value to have one of several types. An intersection requires a value to satisfy multiple types at once.

Q2: How does a type assertion differ from a type conversion?

An assertion tells the compiler how to treat a value's type and has no runtime effect. A conversion changes the value at runtime.

Q3: When do I need a custom type guard?

Use a custom guard when typeof and instanceof cannot distinguish the types you need, such as different interface types.


🧪 Practice Exercises

Exercise 1

Write a function that accepts string | number | boolean and returns a different result for each type: a string's length, a number's square, or the string "true" or "false" for a boolean.

function processValue(value: string | number | boolean) {
    // Add your code here
}

Exercise 2

Define interfaces Square and Circle with side length and radius properties, respectively. Write a function that accepts their intersection type and returns their areas.

interface Square {
    sideLength: number;
}

interface Circle {
    radius: number;
}

type Shape = Square & Circle;

function getArea(shape: Shape) {
    // Add your code here
}

🎉 You now understand unions, intersections, type assertions, type guards, and literal types! These concepts form the foundation of safe, robust TypeScript code. Keep practicing to build confidence.