Flexible and Powerful Type Composition - Textnotes

Flexible and Powerful Type Composition


Learn how to combine types in TypeScript using union and intersection types. This module explains union types, intersection types, and real-world use cases with practical examples.

1. Union Types

Union types allow a variable to hold one of multiple possible types. They are defined using the pipe symbol.

Basic Union Type Example


let id: number | string;

id = 101;
id = "A101";

The variable can hold either a number or a string, but not any other type.

Union Types in Functions


function printValue(value: number | string): void {
console.log(value);
}

Inside the function, type narrowing is often required to safely work with the value.

Type Narrowing Example


function formatInput(input: number | string): string {
if (typeof input === "number") {
return input.toFixed(2);
}
return input.toUpperCase();
}

Union of Literal Types


type Status = "success" | "error" | "loading";

let currentStatus: Status = "success";

Literal unions are commonly used for application states and configuration values.

2. Intersection Types

Intersection types combine multiple types into one. A variable using an intersection type must satisfy all included types.

Basic Intersection Type Example


type Person = {
name: string;
};

type Employee = {
employeeId: number;
};

type Staff = Person & Employee;

Using the Intersection Type


let staffMember: Staff = {
name: "Muni",
employeeId: 501
};

Intersection types are useful when an object needs to combine multiple roles or responsibilities.

Intersection with Interfaces


interface LoginInfo {
username: string;
}

interface AccessRights {
role: string;
}

type UserAccess = LoginInfo & AccessRights;

3. Real-World Examples

Handling API Responses


type ApiResponse = string | number | boolean;

function handleResponse(response: ApiResponse): void {
console.log(response);
}

User Authentication Example


type UserProfile = {
id: number;
name: string;
};

type AuthDetails = {
token: string;
};

type AuthenticatedUser = UserProfile & AuthDetails;

This ensures that an authenticated user always has both profile and authentication information.

Form Input Example


type InputValue = string | number;

function processInput(value: InputValue): void {
if (typeof value === "string") {
console.log(value.trim());
} else {
console.log(value.toString());
}
}

Conclusion

Union and intersection types provide flexibility and strong type safety in TypeScript. Union types allow multiple possible values, while intersection types combine multiple structures into one. These concepts are essential for handling complex data models in real-world applications.