Start Coding

Topics

TypeScript Interface Basics

Interfaces are a powerful feature in TypeScript that define the structure of objects. They serve as contracts, ensuring that objects adhere to a specific shape.

What are Interfaces?

An interface in TypeScript is a way to define a type that describes the properties and methods an object should have. It's a blueprint for object structures, promoting code consistency and type safety.

Syntax and Usage

To declare an interface, use the interface keyword followed by the interface name and its members:


interface Person {
    name: string;
    age: number;
    greet(): void;
}
    

You can then use this interface to type-check objects:


const john: Person = {
    name: "John Doe",
    age: 30,
    greet() {
        console.log(`Hello, I'm ${this.name}`);
    }
};
    

Optional Properties

Interfaces can have optional properties, marked with a question mark:


interface Car {
    make: string;
    model: string;
    year?: number;
}
    

This allows for flexibility when implementing the interface. For more details on optional properties, check out the Optional Properties guide.

Readonly Properties

You can make properties immutable using the readonly modifier:


interface Point {
    readonly x: number;
    readonly y: number;
}
    

This prevents accidental modification of the properties after initialization. Learn more about this in the Readonly Properties section.

Implementing Interfaces

Classes can implement interfaces using the implements keyword:


class Student implements Person {
    constructor(public name: string, public age: number) {}
    greet() {
        console.log(`Hi, I'm ${this.name}, a student.`);
    }
}
    

This ensures that the class adheres to the structure defined by the interface. For a deeper dive, visit the Implementing Interfaces guide.

Best Practices

  • Use interfaces to define contracts for object shapes.
  • Prefer interfaces over type aliases for object types.
  • Keep interfaces focused and single-purpose.
  • Use meaningful names that describe the object's role or purpose.
  • Consider using interfaces for function types when they are complex or reused.

Conclusion

Interfaces are a cornerstone of TypeScript, providing robust type checking and improving code organization. They offer a flexible way to define object structures and promote code reusability.

As you delve deeper into TypeScript, you'll find interfaces invaluable for creating maintainable and scalable code. To explore more advanced concepts, check out Extending Interfaces and Interfaces vs Type Aliases.