Generic interfaces

We can also use interfaces with the generic type syntax. If we were to create an interface for our FootballClubPrinter generic class, the interface definition would be as follows:

interface IFootballClubPrinter < T extends IFootballClub > { 
    print(arg : T); 
    IsEnglishTeam(arg : T); 
} 

This interface looks identical to our class definition, with the only difference being that the print and the IsEnglishTeam functions do not have an implementation. We have kept the generic type syntax using < T >, and further specified that the type T must implement the IFootballClub interface. To use this interface with the FootballClubPrinter class, we can modify the class definition, as follows:

class FootballClubPrinter< T extends IFootballClub > 
    implements IFootballClubPrinter< T > { 
 
} 

This syntax seems pretty straightforward. As we have seen before, we use the implements keyword following the class definition, and then use the interface name. Note, however, that we pass the type T into the interface definition of IFootballClubPrinter as a generic type IFootballClubPrinter<T>. This satisfies the IFootballClubPrinter generic interface definition.

An interface that defines our generic classes further protects our code from being modified inadvertently. As an example of this, suppose that we tried to redefine the class definition of FootballClubPrinter so that T is not constrained to be of type IFootballClub:

class FootballClubPrinter< T  > 
    implements IFootballClubPrinter< T > { 
 
} 

Here, we have removed the constraint on the type T for the FootballClubPrinter class. TypeScript will automatically generate an error:

error TS2344: Type 'T' does not satisfy the constraint 'IFootballClub'.

This error points us to our erroneous class definition; the type T, as used in the code (FootballClubPrinter<T>), must use a type T that extends from IFootballClub in order to correctly implement the IFootballClubPrinter interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.2.184