- All Courses
- TypeScript Deep Dive
- Generics That Earn Their Keep
- Constraints and defaults
Constraints and defaults
A constraint lets you use a parameter while keeping it generic: constrain it to an object and you can read its keys; constrain it with keyof and a getter can return the exact type…
Overview
Say what the parameter is allowed to be
A constraint lets you use a parameter while keeping it generic: constrain it to an object and you can read its keys; constrain it with keyof and a getter can return the exact type of the property it fetches rather than a union of all of them.
Defaults keep a flexible type approachable. A response type parameterised over its payload can default to unknown, so the common case stays short and the advanced case stays available.
Constrain to what you actually need. Over-constraining rejects valid callers, and under-constraining pushes the error message somewhere unhelpful.
In this lesson you will:
- Restrict a parameter with extends
- Use keyof to type a property accessor
- Give a parameter a sensible default
Resources
Notes are not saved yet — they clear when you leave this page.
Writing your first generic
13m
Conditional and mapped types
4m