TypeScript offers powerful way for organizing code and managing relationships between different components through the use of extends and implements keywords. This article explores the distinctions and functionalities of these two keywords.
ExtendsThe extends keyword is used for two main purposes in TypeScript: inheriting from a class (class inheritance) and extending a type (type extension).
Class InheritanceWhen using extends for class inheritance, a subclass is created that inherits properties and methods from another class.
Syntax (For class inheritance):class DerivedClass extends BaseClass {
// Additional properties and methods in the derived class
} Syntax (For type extension):type ExtendedType = BaseType & {
// Additional properties and methods in the extended type
}; Example 1: In this example, we are using extends for class inheritance
JavaScript
class Animal {
makeSound(): void {
console.log('Dog sound');
}
}
// Derived class representing a
// specific type of animal: Dog
class Dog extends Animal {
bark(): void {
console.log('Dog is barking!');
}
}
const myDog = new Dog();
myDog.makeSound();
myDog.bark();
Output:
Dog sound
Dog is barking! Example 2: In this example, we are using extends for type extension.
JavaScript
type Shape = {
color: string;
};
type Square = Shape & {
sideLength: number;
};
const mySquare: Square = {
color: 'red',
sideLength: 5,
};
console.log(mySquare);
Output:
{ color: 'red', sideLength: 5 } ImplementsThe implements keyword is used to ensure that a class conforms to a particular interface. This enforces that the class implements all the properties and methods defined by the interface.
Syntax:class ClassName implements InterfaceName {
// Class properties and methods
} Example: In this example, the GFG class implements the GeeksForGeeks interface, and it is required to provide an implementation for the print method specified by the interface.
JavaScript
interface GeeksforGeeks {
print(): void;
}
class GFG implements GeeksforGeeks {
print() {
console.log('GeeksForGeeks');
}
}
const output = new GFG();
output.print();
Output:
GeeksForGeeks Difference between extends and implements
Features
| extends
| Implements
|
---|
Inheritance
| Extends is used for class inheritance. It allows a class to inherit properties and methods from another class.
| Implements is used for interface implementation. It enables a class to provide specific implementations for the methods defined in an interface.
|
---|
Multiple Inheritance
| A class can extend only one class
| A class can implement multiple interfaces
|
---|
Implementation of Methods
| No direct implementation of methods.
| Requires the class to provide concrete implementations for all methods declared in the interface.
|
---|
Code Reusability
| Promotes code reusability
| Promotes code reusability and abstraction through interfaces.
|
---|
Abstract Classes
| Can extend abstract classes
| Cannot extend abstract classes but can implement abstract methods.
|
---|
|