Labs ICT
โญ Pro Login

Interfaces

Interfaces are TypeScript's way of defining object shapes. They specify what properties an object must have and what types those properties should be. Think of interfaces as blueprints for your objects - they tell TypeScript exactly what you're expecting and catch any missing or extra properties before runtime.

Defining Object Shapes

Interfaces are perfect for creating consistent object structures across your application. You can define required properties with mandatory fields, optional properties with `?`, and strict interfaces that require exactly those properties. This helps you build APIs and data structures with predictable shapes.


interface User {
    readonly id: number;
    name: string;
    email?: string;
    getName(): string;
}

interface ReadOnlyUser {
    readonly [key: string]: string | number;
}

const user: User = {
    id: 1,
    name: "Alice",
    email: "alice@example.com",
    getName() {
        return this.name;
    }
};

// Partial interface for updates
interface UpdateUser {
    name?: string;
    email?: string;
}

const updated: Partial = { name: "Alice Smith" };
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

How do you define an interface in TypeScript?