Labs ICT
โญ Pro Login

Type Aliases

Type aliases let you create custom types with complex shapes. You can define function signatures, object structures, or combination types. They're perfect for creating reusable type definitions and keeping your code DRY. Think of them as creating your own type names for complex or frequently used type structures.

Creating Custom Types

Use type aliases to abstract complex type expressions into simple, readable names. They work with primitive types, object types, function types, and combinations. Type aliases are ideal for complex types that would make your code hard to read if written inline repeatedly.


// Simple type aliases
type StringOrNumber = string | number;
type UserId = number;
type UserName = string;

// Function types
type Callback = (value: T) => void;
type AsyncCallback = (error: Error | null, data?: any) => void;

// Object types
type UserProfile = {
    id: number;
    username: string;
    email: string;
    isActive: boolean;
};

// Complex types
type ApiResponse = {
    data: T;
    status: number;
    message?: string;
};

type EventHandlers = {
    [key: string]: (event: Event) => void;
};

// Utility type
type Partial = {
    [P in keyof T]?: T[P];
};

const userId: UserId = 123;
const processValue: Callback = (value) => {
    console.log(`Processing: ${value}`);
};

const response: ApiResponse = {
    data: { id: 1, username: "alice", email: "alice@example.com", isActive: true },
    status: 200,
    message: "Success"
};
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

How do you create a type alias in TypeScript?