TypeScript

Interfaces in TypeScript: A Comprehensive Guide

An interface describes the shape of an object. It says "anything that claims to be this type must have these properties." It doesn't contain any implement...

23 Apr 2024

Interfaces in TypeScript: A Comprehensive Guide

An interface describes the shape of an object. It says "anything that claims to be this type must have these properties." It doesn't contain any implementation — just a contract.

Typescript
interface Person {
  name: string;
  age: number;
}

Any object matching this shape satisfies the interface. No implements keyword required for plain objects:

Typescript
const person: Person = {
  name: 'John',
  age: 30
};

If you try to assign an object missing age, TypeScript stops you at compile time. That's the whole point.

Interfaces with classes

When you use a class, implements makes the contract explicit:

Typescript
class Employee implements Person {
  constructor(public name: string, public age: number) {}

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

The class must satisfy every property and method the interface defines. If it doesn't, the compiler tells you immediately.

Why interfaces matter

  • Catch shape mismatches early. Pass the wrong object to a function and the compiler flags it before runtime.
  • Enable refactoring. Rename a property in the interface and TypeScript shows you every place that needs updating.
  • Document contracts. Reading an interface tells you exactly what a function expects without reading its implementation.

Interface vs Type

In TypeScript, type and interface overlap significantly. Both can describe object shapes. The differences:

  • Interfaces support declaration merging (defining the same interface twice combines them). Types don't.
  • Types support unions and intersections more naturally (type Result = Success | Error).

I use interfaces for object shapes and public API contracts. I use types for unions, intersections, and computed types. But either works in most situations.