Skip to the workspace
Pebellslearn by building
TypeScript Interfaces  ›  Lesson

Declaring an Interface

Interface Declaration 12 minAn interface declares a named object shape with required, optional and readonly properties and method signatures.

typescript / Declaring an Interface

Explore each scene at your own pace.

01 · The rule

The rule

Declaring an Interface

An interface declares a named object shape with required, optional and readonly properties and method signatures.

Describe the fields and operations that a consumer expects from an object.

You have been writing object shapes with type Task = {...}. Open almost any TypeScript codebase or library, though, and you will see the other way of naming a shape everywhere: interface. This section makes it yours, starting with how to declare one.

The rule

An interface is a named object shape: properties, modifiers and methods.

interface Task {
  readonly id: number;
  title: string;
  done: boolean;
  notes?: string;
  complete(): void;
}

Line by line:

  • title: string — a required property. Every Task must have it.
  • notes?: string — optional. It may be missing, so reading it gives a string or undefined.
  • readonly id: number — can be set when the object is created but not reassigned afterwards. This is a compile-time rule only.
  • complete(): void — a method signature: every Task has a complete method that takes no arguments and returns nothing useful.

Members can be separated by semicolons, commas, or just line breaks. Interfaces are erased at compile time; they only describe shapes.

Two more members you will meet often:

interface TaskIndex {
  [id: string]: Task;          // index signature: any string key maps to a Task
}

interface Formatter {
  (task: Task): string;        // call signature: the value itself is a function
}

An index signature describes objects used as dictionaries, where you do not know the key names in advance. A call signature describes something you can call like a function.

A class can promise to follow an interface with implements. The compiler then checks that the class really has every member:

class SimpleTask implements Task {
  readonly id: number;
  title: string;
  done = false;
  constructor(id: number, title: string) {
    this.id = id;
    this.title = title;
  }
  complete(): void { this.done = true; }
}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.