Objects & Interfaces
Interfaces — Defining & Implementing
Master defining interfaces in TypeScript, implementing interfaces in ES6 classes, property contracts, method contracts, and strict interface enforcement.
An Interface in TypeScript is a powerful way to define a structural contract for objects, functions, and classes. It specifies what properties and methods an object or class must contain, without dictating how they are implemented.
1. Defining Interfaces
Use the interface keyword followed by the interface name:
2. Implementing Interfaces in Classes (implements)
Classes use the implements keyword to guarantee that they satisfy an interface contract. If a class fails to declare any property or method required by the interface, TypeScript raises a compile error.
3. Method Signatures in Interfaces
Interfaces can describe methods using either Method Shorthand Syntax or Property Function Syntax:
4. Interactive Code Playground
Test interface definitions and class implementations below:
5. Common Pitfalls & Edge Cases
implements Does NOT Infer Parameter Types in Classes: When implementing an interface in a class, TypeScript requires parameter type annotations inside the class constructor/method headers.6. Summary Table
| Concept | Syntax | Description |
|---|---|---|
| Interface Declaration | interface Name { prop: Type; } | Defines object/class shape contract |
| Class Implementation | class Foo implements Name | Enforces shape on ES6 class instance |
class Foo implements A, B | Implements multiple independent interfaces |