Chapter 4. Generics
Until now, our main goal was to take the inherent flexibility of JavaScript and find a way to formalize it through the type system. We added static types for a dynamically typed language, to communicate intent, get tooling, and catch bugs before they happen.
Some parts in JavaScript don’t really care about static types, though. For example, an isKeyAvailableInObject function should only check if a key is available in an object; it doesn’t need to know about the concrete types. To properly formalize a function like this we can use TypeScript’s structural type system and describe either a very wide type for the price of information or a very strict type for the price of
flexibility.
But we don’t want to pay any price. We want both flexibility and information. Generics in TypeScript are just the silver bullet we need. We can describe complex relationships and formalize structure for data that has not been defined yet.
Generics, along with its gang of mapped types, type maps, type modifiers, and helper types, open the door to metatyping, where we can create new types based on old ones and keep relationships between types intact while the newly generated types challenge our original code for possible bugs.
This is the entrance to advanced TypeScript concepts. But fear not, there shan’t be dragons, unless we define them.
4.1 Generalizing Function Signatures
Problem
You have two functions that work the same, but on different and largely incompatible types.
Solution ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access