TYPESCRIPT / CHAPTER 07
Preserve relationships with generics
IntermediateConnect input and output types without discarding information.
By the end of this chapter
- Use a type parameter to preserve element types
- Constrain supported operations
- Express a key-dependent return type
The idea
A generic function describes a relationship between types rather than choosing one concrete type. If a function returns an element from its input array, a type parameter can preserve whether that element is a string, number, or record. Replacing everything with any loses that relationship and permits operations the actual values may not support.
Constraints state the minimum capabilities required by an implementation. A function that reads length can require a length property without requiring one particular collection. For object access, K extends keyof T connects the chosen key to the object, and T[K] describes that property’s value type. Keep parameters meaningful: introduce them when they connect positions in a contract, not merely to make a simple function look flexible.
function read<T, K extends keyof T>(record: T, key: K): T[K] {
return record[key];
}
const item = {name: "Panel", count: 3};
console.log(read(item, "count"));3
The key constraint excludes keys that do not exist on the inferred object type. The return type follows the selected property.
Try it yourself
Write first<T> for a readonly array, returning T | undefined for an empty input.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING