What’s the Difference Between ‘extends’ and ‘implements’ in TypeScript ?
Last Updated :
18 Dec, 2023
In TypeScript, extends
and implements
are primarily used to define relationships between types and classes. In this article, we will learn the difference between ‘extends’ and ‘implements’ in TypeScript.
Extends
extends
is used to create a subclass that inherits properties and methods from another class or to extend a type by including properties from another type.
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' );
}
}
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 }
Implements
Implements
is used in a class to indicate that the class is going to implement a particular interface. It ensures that the class includes all the properties and methods specified 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
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.
|
A class can extend only one class
|
A class can implement multiple interfaces
|
No direct implementation of methods.
|
Requires the class to provide concrete implementations for all methods declared in the interface.
|
Promotes code reusability
|
Promotes code reusability and abstraction through interfaces.
|
Can extend abstract classes
|
Cannot extend abstract classes but can implement abstract methods.
|
Share your thoughts in the comments
Please Login to comment...