Generics
20 steps in 4 sets of TypeScript.
Type parameters, and then the part people skip: reading types rather than only writing them. keyof, typeof, indexed access, and the inference rules that mean most code needs no annotations at all.
Generic helper types close it. Twenty steps, and this is where TypeScript stops feeling like annotations on JavaScript and starts feeling like a language of its own.
Type parameters
- GenericsFunctions and types that work over any type.
- Constraints and defaultsA type parameter can be bounded, and can have a default.
- InferenceWhere TypeScript works the type out, and how to help it.
- VarianceWhere a subtype is accepted, and the annotations that say so.
Reading types
- keyof and indexed accessThe two operators every generic helper is built from.
- Reading types off valuestypeof lifts a value's type; ReturnType and InstanceType go further.
- Utility typesThe built-in type transformers you reach for daily.
- The utility typesThe built-ins worth memorising, and what each one is for.
Generic helpers
- Pick keys from objectSelects keys from an object and gets a correctly narrowed type back.
- Generic group byGroup by a key function, with the return type derived from the key.
- Index by keyIndexes an array into a record keyed by one of its fields.
- Group entries by valueGroups object entries by their value.
- Partition by predicateSplits an array in two by a predicate, narrowing the type when the predicate is a guard.
- Minimum by keyFinds the smallest item by a computed value, returning undefined for an empty array.
- Unique by keyDeduplicates by a computed key, with the key type inferred.
- Typed zipPairs parallel arrays into typed tuples.
- Chunk an arraySplits an array into fixed-size pieces, generic in the element.
- Binary searchBinary search over a sorted array, generic in the element type.
- Map over an optionalApplies a function only when the value is not null or undefined.
Encore
- inventory.tsA complete inventory script: typed records in, grouped and totaled report out.