- All Courses
- TypeScript Deep Dive
- Generics That Earn Their Keep
- Writing your first generic
Writing your first generic
A generic is worth adding when two positions in a signature must agree — the element of the array you pass in and the element you get back.
Overview
A type parameter is a relationship
A generic is worth adding when two positions in a signature must agree — the element of the array you pass in and the element you get back. If a type parameter appears only once in a signature, it is not relating anything and a plain type would say the same thing more clearly.
Good generic APIs are inferred, not annotated. If callers have to spell out the parameter every time, the signature has failed at the one job it had.
Name parameters for what they mean. A tree of T, U, and V is legal and unreadable.
In this lesson you will:
- Link an input type to an output type
- Let inference do the work at the call site
- Know when a generic is not needed
Resources
Notes are not saved yet — they clear when you leave this page.
unknown, never, and the any escape hatch
8m
Constraints and defaults
3m