BudiBadu Logo
Samplebadu

TypeScript by Example: Interfaces

5.x

Learn how to define object structures using TypeScript interfaces with this code example. Covers required properties, optional fields using the question mark syntax, readonly modifiers for immutability, and enforcing type contracts across your codebase.

Code

interface User {
    name: string;
    id: number;
    // Optional property
    email?: string;
    // Readonly property
    readonly createdAt: Date;
}

function printUser(user: User) {
    console.log(`User ${user.name} (ID: ${user.id})`);
}

let myUser: User = { 
    name: "Alice", 
    id: 1, 
    createdAt: new Date() 
};

printUser(myUser);

// myUser.createdAt = new Date(); // Error: Cannot assign to 'createdAt' because it is a read-only property.

Explanation

Interfaces are a core way to define the structure or "shape" of objects in TypeScript. They allow you to enforce that an object has specific properties with specific types. You can mark properties as optional using ?, meaning they don't have to be present in the object.

You can also mark properties as readonly. This ensures that the property can only be modified when the object is first created. Attempting to assign to it later will result in a compiler error.

Interfaces are purely a compile-time construct; they do not generate any JavaScript code. They are used solely for type checking and providing better tooling support (like autocompletion).

Code Breakdown

1
interface User defines the object structure contract.
5
email?: string is an optional property using ?.
7
readonly createdAt prevents reassignment after creation.
10
user: User enforces the parameter must match the interface.