Interfaces

Object Shapes With a Few Extra Powers

Interfaces

`interface` is another way to describe an object's shape. It supports `extends` and declaration merging.

4 min read Level 1/5 #typescript#interface#types
What you'll learn
  • Author an interface
  • Use `extends` for inheritance
  • Pick between `type` and `interface`

interface is another way to describe an object shape. It looks similar to a type alias but has a few extras — extends and declaration merging.

The Syntax

interface User {
  id: string;
  name: string;
  age: number;
}

const u: User = { id: "1", name: "Ada", age: 36 };

Notice: no =. interface User { ... }, not interface User = { ... }.

Extending Another Interface

interface BaseUser {
  id: string;
  name: string;
}

interface Admin extends BaseUser {
  permissions: string[];
}

const a: Admin = { id: "1", name: "Ada", permissions: ["read"] };

extends brings in all of BaseUser’s fields. You can extend multiple interfaces:

interface Logger { log(msg: string): void; }
interface Cache  { get(key: string): unknown; }

interface AppService extends Logger, Cache {
  version: string;
}

Declaration Merging

You can define an interface in multiple places and TS merges them:

interface Window {
  myCustomGlobal: string;
}

// elsewhere
interface Window {
  anotherOne: number;
}

// The Window type now has BOTH properties.

type aliases can’t do this. Useful for extending built-in / library types — and a source of subtle bugs if you do it accidentally.

interface vs type — When to Use Which

NeedUse
Object shape, no inheritance, no extensionEither
Inheritance via extendsinterface
Library public API others might extendinterface
Union of typestype
A primitive aliastype
A tupletype
A function typetype
Mapped or conditional typestype

For most app code, type is the safe default. Reach for interface when you actively benefit from extends or want authors to extend it.

Equivalent Forms

type User = {
  id: string;
  name: string;
};

interface User {
  id: string;
  name: string;
}

For this exact shape, both are interchangeable in usage.

Up Next

A | B — unions, the bedrock of TS modeling.

Unions →