Search⌘ K
AI Features

Limitations of Generic Code: Interfaces and Constrained Types

Understand the limitations of using generics with interfaces in TypeScript by exploring how generic code can only access properties common across constrained types. Learn why unique properties in interfaces cannot be referenced in generic functions and how TypeScript enforces this to ensure type safety.

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:

TypeScript 4.9.5
// 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 ...