TypeScript Reference ยท Classes, Enums and Decorators
Implementing interfaces in TypeScript classes
Reference for the TypeScript implements clause: make a class satisfy one or more interfaces, understand what it checks, and avoid common misunderstandings.
The implements clause asks the compiler to verify that a class has every member an interface (or object type) requires. A class can implement several interfaces, separated by commas. If something is missing or has the wrong type, the error appears on the class declaration.
implements is purely a check. It does not copy members into the class, does not change the types of members the class declares, and leaves no trace in the emitted JavaScript.
interface Named { name: string } class Person implements Named { constructor(public name: string) {} }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
class C extends Base implements I1, I2<T> { // members }
| Part | Description |
|---|---|
implements |
Comes after extends. The targets can be interfaces, type aliases of object types, or even other classes (their instance type is used). |
| Members | Must be public in the class to satisfy an interface member; private or protected members cannot. |
| Optional members | An interface's optional member may be omitted; if the class declares it, the type must be compatible. |
Edge cases:
implementschecks the instance side only. Static members and constructor signatures cannot be required this way; type a variable as{ new (): T }for that.- Method parameters of an implementing class are not contextually typed from the interface. Annotate them, or they become implicit
any(an error undernoImplicitAny). - Implementing a class (
implements SomeClass) with private members makes your class impossible to satisfy.
Usage notes
- Interfaces are structural, so a class does not need
implementsto be accepted where the interface is expected. The clause documents intent and gives early, local errors. - If you add a member to the interface, every implementing class errors immediately, which is the main benefit in large code bases.
- A class can implement an interface that extends others. The class must provide all inherited members.
- Combine with
extends: inheritance gives behavior,implementsstates the contract. - Prefer interfaces for contracts shared between unrelated classes, abstract classes when you also want shared code.