What's the difference between 'extends' and 'implements' in TypeScript

TypescriptExtendsImplements

Typescript Problem Overview


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 {}

Typescript Solutions


Solution 1 - Typescript

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.

Solution 2 - Typescript

You have classes and interfaces in typescript (and some other OO languages).

An interface has no implementation; it's just a "contract" of what members/method this type has.
For example:

interface Point {
	x: number;
	y: number;
	distance(other: Point): number;
}

Instances that implement this Point interface must have two members of type number: x and y', and one method, distance, which receives another Pointinstance and returns anumber`.
The interface doesn't implement any of those.

Classes are the implementations:

class PointImplementation implements Point {
	public x: number;
	public y: number;
	
	constructor(x: number, y: number) {
		this.x = x;
		this.y = y;
	}
	
	public distance(other: Point): number {
		return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
	}
}

(code in playground)

In your example, you treat your Person class once as a class when you extend it and once as an interface when you implement it.
Your code:

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

class Man implements Person {}

It has a compilation error saying:

> Class 'Man' incorrectly implements interface 'Person'. > Property' name' is missing in type 'Man'.

And that's because interfaces lack implementation.
So if you implement a class, then you only take its "contract" without the implementation, so you'll need to do this:

class NoErrorMan implements Person {
	name: string;
	age: number;
}

(code in playground)

The bottom line is that you want to extend another class in most cases and not to implement it.

Solution 3 - Typescript

Extends VS implements

  • extends: The child class (which is extended) will inherit all the properties and methods of the class is extends
  • implements: The class which uses the implements keyword will need to implement all the properties and methods of the class which it implements

To put in simpler terms:

  • extends: Here you get all these methods/properties from the parent class so you don't have to implement this yourself
  • implements: Here is a contract which the class has to follow. The class has to implement at least the following methods/properties

Example:

class Person {
  name: string;
  age: number;

  walk(): void {
    console.log('Walking (person Class)')
  }

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
class child extends Person { }

// Man has to implements at least all the properties
// and methods of the Person class
class man implements Person {
  name: string;
  age: number

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  walk(): void {
    console.log('Walking (man class)')
  }

}

(new child('Mike', 12)).walk();
// logs: Walking(person Class)

(new man('Tom', 12)).walk();
// logs: Walking(man class)

In the example we can observe that the child class inherits everything from Person whereas the man class has to implement everything from Person itself.

If we were to remove something from the man class for example the walk method we would get the following compile time error:

> Class 'man' incorrectly implements class 'Person'. Did you mean to > extend 'Person' and inherit its members as a subclass? Property > 'walk' is missing in type 'man' but required in type 'Person'.(2720)

Solution 4 - Typescript

Great Answer from @nitzan-tomer! Helped me a lot... I extended his demo a bit with:

IPoint interface;
Point implements IPoint;
Point3D extends Point;

And how they behave in functions expecting an IPoint type.

So what I've learned so far and been using as a thumb-rule: If you're using classes and methods expecting generic types, use interfaces as the expected types. And make sure the parent or base-class uses that interface. That way you can use all subclasses in those as far as they implement the interface.

Here the [extended demo][1]

[1]: https://www.typescriptlang.org/play/index.html#src=interface%20IPoint%20%7B%0A%20%20%20%20x%3A%20number%3B%0A%20%20%20%20y%3A%20number%3B%0A%20%20%20%20distance(other%3A%20IPoint)%3A%20number%3B%0A%7D%0A%0Aclass%20Point%20implements%20IPoint%20%7B%0A%09public%20x%3A%20number%3B%0A%09public%20y%3A%20number%3B%0A%09%0A%09constructor(x%3A%20number%2C%20y%3A%20number)%20%7B%0A%09%09this.x%20%3D%20x%3B%0A%09%09this.y%20%3D%20y%3B%0A%09%7D%0A%09%0A%09public%20distance(other%3A%20Point)%3A%20number%20%7B%0A%09%09return%20Math.sqrt(Math.pow(this.x%20-%20other.x%2C%202)%20%2B%20Math.pow(this.y%20-%20other.y%2C%202))%3B%0A%09%7D%0A%7D%0A%0Aclass%20Point3D%20extends%20Point%20%7B%0A%09z%3A%20number%3B%0A%0A%09constructor(x%3A%20number%2C%20y%3A%20number%2C%20z%3A%20number)%20%7B%0A%09%09super(x%2C%20y)%3B%0A%09%09this.z%20%3D%20z%3B%0A%09%7D%0A%0A%09distance(other%3A%20Point3D)%3A%20number%20%7B%0A%09%09return%201000%20%2B%20other.z%20%2B%20super.distance(other)%3B%0A%09%7D%0A%7D%0A%0Aconst%20p1%20%3D%20new%20Point(1%2C%202)%3B%0Aconst%20p2%20%3D%20new%20Point(2%2C%202)%3B%0Aconst%20p3d_1%20%3D%20new%20Point3D(1%2C%201%2C%201)%3B%0Aconst%20p3d_2%20%3D%20new%20Point3D(5%2C%205%2C%205)%3B%0A%0Aconsole.log('p1%20-%20p2%3A'%2C%20p1.distance(p2))%3B%0Aconsole.log('p1%20-%20p3d_1'%2C%20p1.distance(p3d_1))%3B%20%2F%2F%20p3d_1%20acts%20like%20Point%0A%2F%2Fp3d_1.distance(p1))%3B%20%3C-%20error%20because%20p1%20is%20not%20Point3D%0Aconsole.log('p3d_1%20-%20p3d_2'%2C%20p3d_1.distance(p3d_2))%3B%20%2F%2F%203D%20distance%0A%0Afunction%20myTypes(p%3A%20IPoint)%20%7B%0A%09let%20types%20%3D%20%5B%5D%3B%0A%0A%09if%20(p%20instanceof%20Point3D)%20%7B%0A%09%09types.push('Point3D')%3B%0A%09%7D%0A%09if%20(p%20instanceof%20Point)%20%7B%0A%09%09types.push('Point')%3B%0A%09%7D%0A%09console.log('My%20types%3A'%2C%20types)%3B%0A%7D%0A%0AmyTypes(p1)%3B%20%2F%2F%20%5B'Point'%5D%0AmyTypes(p3d_1)%3B%20%2F%2F%20%5B'Point3D'%2C%20'Point'%5D

Solution 5 - Typescript

  1. Interface extends interface with shape
  2. Interface extends class with shape
  3. Class implements interface should implements all fields provided by the interface
  4. Class implements class with shape
  5. Class extends class with all fields

extends focus on inherit and implements focus on constraint whether interfaces or classes.

Solution 6 - Typescript

Basically:

  • extends will get all properties and methods of the parent class.
  • implements will obligate us to implement all of the properties and methods defined in the interface.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondavejoemView Question on Stackoverflow
Solution 1 - TypescriptRadim KöhlerView Answer on Stackoverflow
Solution 2 - TypescriptNitzan TomerView Answer on Stackoverflow
Solution 3 - TypescriptWillem van der VeenView Answer on Stackoverflow
Solution 4 - TypescriptandzepView Answer on Stackoverflow
Solution 5 - Typescriptlei liView Answer on Stackoverflow
Solution 6 - TypescriptPouya JabbarisaniView Answer on Stackoverflow