implements

A declaration that a class fulfills the contract described by an interface.

On this page

Example

#
TypeScript
interface Scorable {
  score(): number
}

class Quiz implements Scorable {
  constructor(private correct: number, private total: number) {}

  score(): number {
    return Math.round((this.correct / this.total) * 100)
  }
}

const quiz = new Quiz(8, 10)
console.log(`Score: ${quiz.score()}%`)
Result
Score: 80%

Definition and usage

#

The implements keyword after a class name tells the compiler that the class must have all the fields and methods from the given interface. If something is missing or the types don’t match, an error appears.

This check only concerns types: implements inherits no code at all. The class has to implement every method itself. For inheriting code, use extends between classes.

One class can implement several interfaces, which lets you describe independent capabilities, for example Serializable and Comparable.

Syntax

#
Syntax
class Name implements Interface1, Interface2 {
  

}

More examples

#
A missing method
TypeScript
class Exam implements Scorable {}
// Error: Class 'Exam' incorrectly implements interface 'Scorable'.
//   Property 'score' is missing in type 'Exam' but required in type 'Scorable'.

Good practices

#
  • implements doesn’t change the types inside the class. You still have to type the method parameters in the class itself.
  • Interfaces that describe capabilities (what an object can do) combine better than deep class inheritance.

Related entries

#

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