Labs ICT
โญ Pro Login

Union & Intersection

1 min read | TypeScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Union and intersection types give you the power to describe complex data relationships. Union types (`|`) let you say "this could be one of these types," while intersection types (`&`) let you combine multiple types into one. These are essential for building robust type systems that accurately reflect your application's data structures.

Union and Intersection Types

Use union types when a value can be one of several different types, like a user's status that could be "active", "inactive", or "pending". Intersection types come in handy when you need to combine multiple type requirements, like creating a User object that has both an ID and authentication properties.


// Union types
let status: "active" | "inactive" | "pending" = "active";
let id: string | number = "user123";

// Type narrowing with typeof
function processValue(value: string | number) {
    if (typeof value === "string") {
        return value.toUpperCase();
    } else {
        return value * 2;
    }
}

// Intersection types
interface BaseUser {
    id: number;
    name: string;
}

interface AdminUser {
    permissions: string[];
    role: "admin";
}

type FullUser = BaseUser & AdminUser;
const admin: FullUser = { id: 1, name: "Bob", permissions: ["read", "write"], role: "admin" };
    

๐Ÿงช Quick Quiz

Which symbol represents a union type in TypeScript?