...

/

Limitations of Generic Code: Interfaces and Constrained Types

Limitations of Generic Code: Interfaces and Constrained Types

Learn about the limitations of generic code and how to use interfaces to constrain the type of T and reference common properties and functions.

We have already seen how we can constrain the type of T in our generic code in order to limit the number of types that can be used. Another limit of generic code is that it can only reference functions or properties of objects that are common to any type of T.

Interfaces and constrained type

As an example of this limitation, consider the following code:

// Define an interface IPrintId with id property of type
// number and print method with no return value.
interface IPrintId {
id: number;
print(): void;
}
// Define an interface IPrintName with name property of type
// string and print method with no return value.
interface IPrintName {
name: string;
print(): void;
}
Interfaces for printing id and name
  • We have two interfaces named IPrintId and IPrintName. Both interfaces have a function named print ...