Introduction to implements in TypeScript
The implements keyword in TypeScript allows a class to declare that it satisfies a particular interface. An interface defines a contract that describes the properties and methods an object should provide, while a class supplies the actual implementation.
For example, an application might support different notification services, payment providers, or data storage systems. Each implementation may perform its work differently, but the application can require every implementation to expose the same set of methods.
Interfaces help separate what an object must do from how it does it. When a class uses implements, TypeScript checks whether the class's publicly accessible instance members satisfy the interface contract.
This feature is useful for designing maintainable applications, writing reusable services, supporting interchangeable implementations, and detecting missing or incorrectly typed members during development.
1. Understanding the implements Keyword
The implements keyword appears after a class name and before the class body. It identifies the interface whose contract the class intends to satisfy.
interface Printable {
print(): void;
}
class Report implements Printable {
print(): void {
console.log("Printing report...");
}
}
const report = new Report();
report.print();
The Printable interface requires a method named print that takes no arguments and returns void. Report implements that method, so the class satisfies the interface.
If Report did not provide the required print method, TypeScript would report a compilation error. The same applies if the method's parameter or return type were incompatible with the interface contract.
The interface specifies the expected structure rather than the method's implementation details. Report decides what should happen when print is called.
2. Implementing Interface Properties
An interface can describe the properties that a class must expose. The implementing class must provide compatible public instance properties or other members that satisfy the interface requirements.
interface User {
id: number;
name: string;
email: string;
}
class AppUser implements User {
id: number;
name: string;
email: string;
constructor(id: number, name: string, email: string) {
this.id = id;
this.name = name;
this.email = email;
}
displayInfo(): string {
return this.name + " - " + this.email;
}
}
const user = new AppUser(
101,
"Abhinash",
"abhi@example.com"
);
console.log(user.displayInfo());
The User interface requires id, name, and email. AppUser provides all three properties with compatible types and therefore satisfies the contract.
The class can also define additional properties and methods, such as displayInfo, that are not specified by the interface. Implementing an interface does not prevent a class from providing extra functionality.
With strict property initialization enabled, TypeScript also checks whether the class properties are initialized appropriately. In this example, the constructor assigns values to all required properties.
3. Implementing Interface Methods
Interfaces can define method signatures, including parameter types and return types. A class implementing the interface must provide compatible implementations for its required methods.
interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}
class BasicCalculator implements Calculator {
add(a: number, b: number): number {
return a + b;
}
subtract(a: number, b: number): number {
return a - b;
}
}
const calculator = new BasicCalculator();
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
Calculator defines two required methods. BasicCalculator implements both operations and returns numeric results as specified by the interface.
The class cannot omit a required method or provide an incompatible signature and still satisfy the contract under TypeScript's normal type checking.
Method signatures are especially valuable when several classes must expose common behavior but use different internal logic. The interface gives other parts of the application a consistent way to interact with each implementation.
4. Understanding Optional Interface Properties
An interface can mark a property as optional by placing a question mark after its name. A class implementing that interface does not have to provide the optional property.
interface Employee {
id: number;
name: string;
department?: string;
}
class StaffMember implements Employee {
constructor(
public id: number,
public name: string,
public department?: string
) {}
getDepartment(): string {
return this.department ?? "Unassigned";
}
}
const employee1 = new StaffMember(
101,
"Abhinash",
"Engineering"
);
const employee2 = new StaffMember(102, "Ravi");
console.log(employee1.getDepartment());
console.log(employee2.getDepartment());
The department property is optional in Employee, so an implementing class does not need to require it. StaffMember chooses to expose it as an optional constructor property.
Optional properties are useful when a model supports incomplete information, optional configuration, or fields that may not be available for every object.
Optionality is not the same as nullability. An optional property may be absent, while whether it can explicitly contain null depends on its declared type. With exactOptionalPropertyTypes enabled, assignments involving undefined are also checked more precisely.
5. Using readonly Properties in Interfaces
Interfaces can declare properties as readonly. This tells TypeScript that those properties should not be reassigned through a reference typed with that interface.
interface Product {
readonly id: number;
name: string;
price: number;
}
class StoreProduct implements Product {
constructor(
public readonly id: number,
public name: string,
public price: number
) {}
updatePrice(newPrice: number): void {
if (newPrice >= 0) {
this.price = newPrice;
}
}
}
const product = new StoreProduct(101, "Keyboard", 499);
product.updatePrice(599);
console.log(product.id);
console.log(product.price);
// Compilation error:
// product.id = 202;
The id property is readonly in the interface and is also declared readonly in StoreProduct. The name and price properties remain mutable.
Readonly is a compile-time restriction, not a runtime freezing mechanism. It does not guarantee that every reference to the underlying object is immutable, and it does not automatically make nested objects readonly.
Use readonly for identifiers and values that should not be reassigned through the intended API, while keeping genuinely mutable state writable when appropriate.
6. Implementing Multiple Interfaces
A TypeScript class can implement multiple interfaces. This is useful when an object needs to satisfy several independent contracts, such as providing both logging and notification functionality.
interface Logger {
log(message: string): void;
}
interface Notifier {
notify(message: string): void;
}
class AppService implements Logger, Notifier {
log(message: string): void {
console.log("Log:", message);
}
notify(message: string): void {
console.log("Notification:", message);
}
}
const service = new AppService();
service.log("User registered");
service.notify("Welcome to the application");
AppService implements Logger and Notifier. It must provide compatible implementations of both log and notify.
Unlike class inheritance, which permits a class to extend only one class directly, implementing multiple interfaces lets a class satisfy several contracts at the same time.
This is useful for separating responsibilities into focused interfaces. Instead of defining one large interface for every operation, you can define smaller contracts and combine them where necessary.
7. Combining extends and implements
A class can extend a base class and implement one or more interfaces. In this arrangement, the base class supplies shared implementation, while the interfaces declare additional contracts the class must satisfy.
interface Exportable {
exportData(): string;
}
abstract class DocumentBase {
constructor(public title: string) {}
getTitle(): string {
return this.title;
}
}
class Report extends DocumentBase implements Exportable {
constructor(
title: string,
public content: string
) {
super(title);
}
exportData(): string {
return this.getTitle() + "\n" + this.content;
}
}
const report = new Report(
"Monthly Report",
"Revenue increased this month."
);
console.log(report.exportData());
DocumentBase provides the title property and getTitle method. Exportable defines the exportData contract, and Report supplies its implementation.
The class uses extends to inherit behavior and implements to satisfy an interface contract.
When both keywords are used, the base class is named after extends and the interfaces follow implements. This combination is useful when a class needs shared state and behavior as well as additional capabilities defined by interfaces.
8. Understanding Generic Interfaces with implements
Interfaces can use generics to describe contracts that work with different data types. A class can implement a generic interface by choosing a specific type or by remaining generic itself.
interface Repository {
save(item: T): void;
getAll(): T[];
}
interface User {
id: number;
name: string;
}
class UserRepository implements Repository {
private users: User[] = [];
save(user: User): void {
this.users.push(user);
}
getAll(): User[] {
return this.users;
}
}
const repository = new UserRepository();
repository.save({
id: 101,
name: "Abhinash"
});
console.log(repository.getAll());
Repository is generic because it uses a type parameter T to represent the kind of data it stores. UserRepository implements Repository, so its methods must operate on User objects.
The compiler checks the types passed to save and the return type of getAll. Saving a value that does not satisfy the User type produces a type error.
Generic interfaces are useful for repositories, collections, caching, data access, API clients, and other systems that follow the same contract for different models.
9. Implementing an Interface Does Not Create Behavior Automatically
The implements keyword checks a class against an interface contract. It does not automatically copy method implementations or transform class members to match the interface.
interface Identifiable {
id: number;
getId(): number;
}
// Compilation error:
// The class does not provide the required members.
// class User implements Identifiable {}
class User implements Identifiable {
constructor(public id: number) {}
getId(): number {
return this.id;
}
}
const user = new User(101);
console.log(user.getId());
The interface declares the required structure, but the class must provide the actual property and method implementations. TypeScript checks compatibility during compilation.
Interfaces are type-level declarations and are erased from the generated JavaScript. The implements keyword does not add runtime interface metadata or automatically validate objects at runtime.
If an application receives data from an API, file, or user input, runtime validation may still be necessary even when the expected data structure is described by an interface.
10. Implementing Interfaces Does Not Change Class Visibility
An interface describes the public structure that an object must expose. A class cannot satisfy an interface's public property or method requirement by making the corresponding member private or protected.
interface Printable {
print(): void;
}
class Report implements Printable {
private print(): void {
console.log("Printing report");
}
}
// Compilation error:
// Report cannot implement Printable because
// print is private rather than publicly accessible.
The interface expects consumers to call print through an ordinary public reference. Making the method private prevents callers from accessing it, so the class no longer satisfies that public contract.
This is an important distinction when designing interfaces. Interfaces generally describe the operations other parts of the application can rely on, not the internal details a class wants to keep hidden.
A class can still have additional private and protected members that are not part of the interface. Those members remain implementation details while the required interface members stay publicly accessible.
11. Understanding implements and Structural Typing
TypeScript primarily uses structural typing. In many situations, an object can be assigned to an interface-typed variable if its structure satisfies the interface, even when the object was not created from a class that explicitly implements the interface.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
const anotherLogger = {
log(message: string): void {
console.log("Custom:", message);
}
};
const logger1: Logger = new ConsoleLogger();
const logger2: Logger = anotherLogger;
logger1.log("First message");
logger2.log("Second message");
Both values can be assigned to Logger because they provide a compatible log method. The object literal does not need an explicit implements declaration to satisfy the interface.
Explicitly implementing an interface is still valuable because it documents the class's intention and asks TypeScript to check that the class conforms to the declared contract.
Structural typing makes it easier to use interfaces across unrelated implementations without forcing them into the same inheritance hierarchy.
12. Common Mistakes to Avoid
- Forgetting required interface members: a class must provide compatible implementations for all required public instance members.
- Confusing implements with extends: extends establishes a class inheritance relationship, while implements checks whether a class satisfies an interface contract.
- Expecting interface methods to be generated: implements does not create methods or copy behavior into a class.
- Making an interface member private: members required by an interface must remain publicly accessible through the implementing class's contract.
- Assuming interfaces validate runtime objects: interface declarations are erased during compilation and do not automatically check API responses or user input.
- Duplicating large interfaces unnecessarily: focused interfaces can represent smaller capabilities that classes can combine as needed.
- Adding implements without a clear contract: an interface should express a useful requirement that helps callers or maintainers understand the class's expected behavior.
13. Best Practices for implements
- Define interfaces around clear capabilities or responsibilities rather than unrelated collections of methods.
- Use implements when you want TypeScript to check that a class satisfies a particular contract.
- Keep interface-required properties and methods publicly accessible.
- Use generic interfaces when the same contract should work with different data types.
- Combine interfaces with class inheritance only when the design benefits from both shared implementation and additional contracts.
- Use structural typing to work with compatible objects without unnecessary inheritance.
- Prefer smaller interfaces when different classes need different subsets of behavior.
- Remember that interfaces provide compile-time checks; use runtime validation when external data must be verified.
- Keep interface declarations synchronized with the behavior expected by consumers of the class.
Conclusion
The implements keyword allows TypeScript classes to declare that they satisfy an interface contract. Interfaces define the required public structure, while classes provide the concrete properties and methods that make the behavior work.
A class can implement multiple interfaces, work with generic contracts, and combine interface implementation with class inheritance. These capabilities help separate responsibilities and make different implementations interchangeable when they satisfy the same contract.
By creating focused interfaces and using implements to verify class compatibility, you can improve code organization and maintainability. Remember that interfaces and implements are compile-time features, so runtime validation remains important when handling external data.