interface

A named description of an object’s shape that you can extend and merge.

On this page

Example

#
TypeScript
interface Course {
  id: number
  title: string
  modules: number
  describe(): string
}

const html: Course = {
  id: 1,
  title: 'HTML and CSS',
  modules: 11,
  describe() {
    return `${this.title}: ${this.modules} modules`
  }
}

console.log(html.describe())
Result
HTML and CSS: 11 modules

Definition and usage

#

An interface gives a name to the shape of an object: it lists its fields and methods along with their types. An object matches the interface if it has the required properties with matching types. It doesn’t need to be created with any special syntax.

You can extend interfaces with the extends keyword, building more specific types out of general ones. Classes can implement them with implements, which guarantees they have the required methods.

A special feature of interfaces is declaration merging: two interfaces with the same name merge into one. That’s how libraries let you extend their types from the outside, for example adding fields to the Window object.

Syntax

#
Syntax
interface Name {
  field: type
  method(param: type): type
}

More examples

#
Declaration merging
TypeScript
interface Settings {
  theme: 'dark' | 'light'
}

interface Settings {
  sounds: boolean
}

const settings: Settings = { theme: 'dark', sounds: true }
console.log(Object.keys(settings))
Result
['theme', 'sounds']

Good practices

#
  • For describing objects and class contracts, interface is the natural choice. For unions, tuples, and complex types, use type.
  • Name interfaces after what the object is (User, Course), without an I prefix.

Related entries

#

Spotted a mistake or missing an example? Write to us.