Horje
What are ‘implements’ clauses in TypeScript ?

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




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to add CSS in XML File ? How to add CSS in XML File ?
Explain sub-classes and inheritance in ES6 Explain sub-classes and inheritance in ES6
How to get HTML code from loaded WebView ? How to get HTML code from loaded WebView ?
Hibernate - Criteria Queries Hibernate - Criteria Queries
How to Create a Spring Bean in 3 Different Ways? How to Create a Spring Bean in 3 Different Ways?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11