SyntaxStudy
Sign Up
TypeScript Defining and Implementing Interfaces
TypeScript Beginner 1 min read

Defining and Implementing Interfaces

An interface in TypeScript is a named contract that describes the shape of an object. It declares which properties and methods a conforming object must have, along with their types. Interfaces are purely a compile-time construct — they are completely erased from the emitted JavaScript and have no runtime representation. Objects, classes, and function types can all be validated against an interface. When a class uses the implements keyword with an interface, TypeScript verifies that the class provides all required members with the correct types. A class can implement multiple interfaces at once, which is one of the primary mechanisms for achieving interface-based polymorphism in TypeScript. Interfaces support optional properties (marked with ?) and readonly properties. Optional properties let you model objects where some fields may be absent, while readonly properties prevent reassignment after initialisation. These modifiers make interfaces extremely expressive for modelling real-world data shapes and API contracts.
Example
// Basic interface
interface User {
    readonly id: number;
    name: string;
    email: string;
    role?: "admin" | "user"; // optional
}

const alice: User = { id: 1, name: "Alice", email: "alice@example.com" };
// alice.id = 2; // Error: cannot assign to readonly property

// Interface for a function type
interface Formatter {
    (value: string, locale: string): string;
}

const fmt: Formatter = (v, l) => v.toLocaleUpperCase(l);

// Implementing an interface in a class
interface Printable {
    print(): void;
}

interface Serializable {
    serialize(): string;
}

class Report implements Printable, Serializable {
    constructor(private title: string, private body: string) {}

    print(): void {
        console.log(`=== ${this.title} ===\n${this.body}`);
    }

    serialize(): string {
        return JSON.stringify({ title: this.title, body: this.body });
    }
}

const report = new Report("Q1 Summary", "Revenue up 12%.");
report.print();
console.log(report.serialize());

// Index signatures
interface StringMap {
    [key: string]: string;
}

const headers: StringMap = {
    "Content-Type": "application/json",
    "Authorization": "Bearer token123",
};