Skip to content
Related Articles

Related Articles

What are ‘implements’ clauses in TypeScript ?

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 09 Mar, 2022

In Typescript an implements clause can be used to verify that a class conforms to a specific interface. If a class fails to implement an interface correctly, an error will be generated. Classes can implement a single interface or multiple interfaces at once.

Example 1: An interface A is created with has a function display of type void. Class B and Class C implement interface A. Class B doesn’t raise an error as method display is properly implemented but class C has a method Display(), which is different from the method defined in the interface, so typescript compiler raises an error that class ‘C’ incorrectly implements interface ‘A’. 

Javascript




// Creating an interface
interface A {
  display(): void;
}
  
class B implements A {
  display() {
    console.log("B");
  }
}
  
class C implements A {
  
  //  Throws error:  Class 'C' incorrectly
  // implements interface 'A'.
  //  Property 'display' is missing in type
  // 'C' but required in type 'A'.
  Display() {
    console.log("C");
  }
}


Output:

error TS2420: Class 'C' incorrectly implements interface 'A'.
  Property 'display' is missing in type 'C' but required in type 'A'.

    class C implements A {
          ~
          display(): void;
          ~~~~~~~~~~~~~~~~
    'display' is declared here.

Example 2: If an additional property exists in an interface does not make that property exist in the class that implements it unless the properties are defined. In such cases typescript compiler raises errors.

Javascript




interface A {
  propA: number;
  propB: number;
}
  
class B implements A {
  propA = 0;
}
  
const obj = new B();
obj.propB = 3;


Output:

Reference: https://www.typescriptlang.org/docs/handbook/2/classes.html#implements-clauses


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!