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'll cover the following...
We'll cover the following...
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:
Interfaces for printing id and name
-
We have two interfaces named
IPrintIdandIPrintName. Both interfaces have a function namedprint...