In this section, we will explore two powerful features of TypeScript: Union Types and Intersection Types. These types allow for more flexible and expressive type definitions, enabling you to write more robust and maintainable code.

Union Types

What are Union Types?

Union types allow a variable to be one of several types. This is useful when a value can be of multiple types, and you want to handle each type appropriately.

Syntax

The syntax for a union type is a vertical bar (|) separating the possible types.

let value: string | number;

In this example, value can be either a string or a number.

Practical Example

Let's consider a function that can accept either a string or a number and returns a string representation of the input.

function formatValue(value: string | number): string {
    if (typeof value === 'string') {
        return `String: ${value}`;
    } else {
        return `Number: ${value.toFixed(2)}`;
    }
}

console.log(formatValue("Hello")); // Output: String: Hello
console.log(formatValue(123.456)); // Output: Number: 123.46

Exercise

Task: Write a function describeValue that takes a parameter of type boolean | string | number and returns a description of the value.

function describeValue(value: boolean | string | number): string {
    // Your code here
}

// Test cases
console.log(describeValue(true)); // Output: Boolean: true
console.log(describeValue("TypeScript")); // Output: String: TypeScript
console.log(describeValue(42)); // Output: Number: 42

Solution:

function describeValue(value: boolean | string | number): string {
    if (typeof value === 'boolean') {
        return `Boolean: ${value}`;
    } else if (typeof value === 'string') {
        return `String: ${value}`;
    } else {
        return `Number: ${value}`;
    }
}

console.log(describeValue(true)); // Output: Boolean: true
console.log(describeValue("TypeScript")); // Output: String: TypeScript
console.log(describeValue(42)); // Output: Number: 42

Intersection Types

What are Intersection Types?

Intersection types allow you to combine multiple types into one. This means that a value must satisfy all the combined types.

Syntax

The syntax for an intersection type is an ampersand (&) separating the types.

interface Person {
    name: string;
}

interface Employee {
    employeeId: number;
}

type EmployeePerson = Person & Employee;

In this example, EmployeePerson must have both name and employeeId properties.

Practical Example

Let's create a function that accepts an EmployeePerson and returns a formatted string.

interface Person {
    name: string;
}

interface Employee {
    employeeId: number;
}

type EmployeePerson = Person & Employee;

function getEmployeeDetails(employee: EmployeePerson): string {
    return `Name: ${employee.name}, Employee ID: ${employee.employeeId}`;
}

const employee: EmployeePerson = { name: "John Doe", employeeId: 12345 };
console.log(getEmployeeDetails(employee)); // Output: Name: John Doe, Employee ID: 12345

Exercise

Task: Define two interfaces, Car and Electric, and create an intersection type ElectricCar. Write a function describeCar that takes an ElectricCar and returns a description.

interface Car {
    make: string;
    model: string;
}

interface Electric {
    batteryCapacity: number;
}

type ElectricCar = Car & Electric;

function describeCar(car: ElectricCar): string {
    // Your code here
}

// Test case
const myCar: ElectricCar = { make: "Tesla", model: "Model S", batteryCapacity: 100 };
console.log(describeCar(myCar)); // Output: Make: Tesla, Model: Model S, Battery Capacity: 100 kWh

Solution:

interface Car {
    make: string;
    model: string;
}

interface Electric {
    batteryCapacity: number;
}

type ElectricCar = Car & Electric;

function describeCar(car: ElectricCar): string {
    return `Make: ${car.make}, Model: ${car.model}, Battery Capacity: ${car.batteryCapacity} kWh`;
}

const myCar: ElectricCar = { make: "Tesla", model: "Model S", batteryCapacity: 100 };
console.log(describeCar(myCar)); // Output: Make: Tesla, Model: Model S, Battery Capacity: 100 kWh

Summary

In this section, we covered:

  • Union Types: Allowing a variable to be one of several types.
  • Intersection Types: Combining multiple types into one, requiring a value to satisfy all combined types.

These types are powerful tools in TypeScript that help you write more flexible and type-safe code. In the next module, we will delve into more advanced types, starting with Generics.

© Copyright 2024. All rights reserved