πŸš€ OharaLumina

Whats the difference between extends and implements in TypeScript

Whats the difference between extends and implements in TypeScript

πŸ“… | πŸ“‚ Category: Typescript

In the world of TypeScript, building robust and maintainable applications often involves leveraging the power of inheritance and interfaces. Understanding the distinction between extends and implements is crucial for effectively structuring your code and maximizing code reusability. These keywords provide different mechanisms for establishing relationships between classes and interfaces, each with its own strengths and use cases. Choosing the right approach can significantly impact your project’s architecture and long-term maintainability. This article delves into the nuances of extends and implements in TypeScript, providing clear examples and practical guidance to help you make informed decisions in your development process.

Inheritance with extends

The extends keyword facilitates inheritance, allowing a class to inherit properties and methods from a base class. This establishes an “is-a” relationship, where the derived class is a specialized type of the base class. This promotes code reuse and creates a hierarchical structure that reflects the relationships between different entities in your application.

For example, consider a Car class and a SportsCar class. A SportsCar is a Car, inheriting common car features while adding specialized attributes like turbocharged.

Interface Implementation with implements

Interfaces define contracts that classes must adhere to. The implements keyword ensures a class provides implementations for all members defined in an interface. This enforces a specific structure and behavior, promoting consistency and type safety.

Imagine an interface Drivable with a drive() method. Both Car and Bicycle can implement Drivable, even though they are fundamentally different, as long as they provide a concrete implementation of drive(). This illustrates a “can-do” relationship.

Key Differences and Use Cases

The core difference lies in the relationship they establish. extends creates an “is-a” relationship (inheritance), while implements establishes a “can-do” relationship (contract adherence). Choosing the right approach depends on the specific scenario.

Use extends when modeling hierarchical relationships where a class is a specialized version of another. Use implements when you need to ensure a class adheres to a specific contract, regardless of its inheritance hierarchy. Sometimes, combining both is the best approach for complex scenarios.

  • extends: Inheritance, “is-a” relationship.
  • implements: Interface implementation, “can-do” relationship.

Practical Examples

Let’s illustrate with a concrete TypeScript example:

typescript interface Shape { area(): number; } class Circle implements Shape { radius: number; constructor(radius: number) { this.radius = radius; } area(): number { return Math.PI this.radius this.radius; } } class Square implements Shape { side: number; constructor(side: number) { this.side = side; } area(): number { return this.side this.side; } } Both Circle and Square implement the Shape interface, adhering to the contract of having an area() method. This ensures type safety and allows for polymorphism.

Multiple Inheritance with Interfaces

TypeScript allows a class to implement multiple interfaces, achieving a form of multiple inheritance. This enables a class to combine functionalities from different contracts, increasing flexibility.

For instance, a class can implement both Drivable and Flyable, demonstrating the ability to both drive and fly.

  1. Define the interfaces (e.g., Drivable, Flyable).
  2. Implement the interfaces in your class.
  3. Provide concrete implementations for all interface members.

By understanding these concepts, you can write cleaner, more maintainable, and scalable TypeScript code. Check out this helpful resource: TypeScript Documentation.

[Infographic illustrating the difference between extends and implements]

TypeScript’s flexibility in implementing multiple interfaces provides a powerful tool for building complex applications with a focus on modularity and code reuse. This feature allows developers to combine functionalities from different sources without the limitations of traditional single inheritance models. More on interface inheritance here.

Frequently Asked Questions

Q: Can a class extend multiple classes?

A: No, TypeScript only supports single class inheritance but allows multiple interface implementations.

Q: What are the benefits of using interfaces?

A: Interfaces promote code clarity, maintainability, and testability by enforcing contracts and enabling loose coupling.

Choosing between extends and implements in TypeScript depends on the relationship you want to model. extends is for inheritance (“is-a”), while implements is for adhering to a contract (“can-do”). Understanding these distinctions is key to writing efficient and maintainable TypeScript code. Explore further resources like MDN Web Docs on JavaScript Classes and DigitalOcean’s tutorial on TypeScript Interfaces to solidify your understanding. Deepen your knowledge and enhance your TypeScript skills by experimenting with different scenarios and applying these concepts to your projects. Don’t forget to check out TypeScript Playground for interactive learning.

Question & Answer :
I would like to know what Man and Child have in common and how they differ.

class Person { name: string; age: number; } class Child extends Person {} class Man implements Person {} 

Short version

  • extends means:

The new class is a child. It gets benefits coming with inheritance. It has all the properties and methods of its parent. It can override some of these and implement new ones, but the parent stuff is already included.

  • implements means:

The new class can be treated as the same “shape”, but it is not a child. It could be passed to any method where Person is required, regardless of having a different parent than Person.

More …

In OOP (languages like C# or Java) we would use

extends to profit from inheritance.

… Inheritance in most class-based object-oriented languages is a mechanism in which one object acquires all the properties and behaviours of the parent object. Inheritance allows programmers to: create classes that are built upon existing classes …

implements will be more for polymorphism.

… polymorphism is the provision of a single interface to entities of different types…

So we can have a completely different inheritance tree for our class Man:

class Man extends Human ... 

but if we also declare that Man can pretend to be the Person type:

class Man extends Human implements Person ... 

…then we can use it anywhere Person is required. We just have to fulfil Person’s “interface” (i.e. implement all its public stuff).

implement other class? That is really cool stuff

Javascript’s nice face (one of the benefits) is built-in support for duck typing.

“If it walks like a duck and it quacks like a duck, then it must be a duck.”

So, in Javascript, if two different objects have one similar method (e.g. render()) they can be passed to a function which expects it:

function(engine){ engine.render() // any type implementing render() can be passed } 

To not lose that in Typescript, we can do the same with more typed support. And that is where

class implements class 

has its role, where it makes sense.

In OOP languages as C#, no way to do that.

The documentation should help here:

Interfaces Extending Classes

When an interface type extends a class type it inherits the members of the class but not their implementations. It is as if the interface had declared all of the members of the class without providing an implementation. Interfaces inherit even the private and protected members of a base class. This means that when you create an interface that extends a class with private or protected members, that interface type can only be implemented by that class or a subclass of it.

This is useful when you have a large inheritance hierarchy, but want to specify that your code works with only subclasses that have certain properties. The subclasses don’t have to be related besides inheriting from the base class. For example:

class Control { private state: any; } interface SelectableControl extends Control { select(): void; } class Button extends Control implements SelectableControl { select() { } } class TextBox extends Control { select() { } } // Error: Property 'state' is missing in type 'Image'. class Image implements SelectableControl { private state: any; select() { } } class Location { } 

So, while

  • extends means it gets all from its parent
  • implements in this case it’s almost like implementing an interface. A child object can pretend that it is its parent… but it does not get any implementation.

🏷️ Tags: