Lesson 2.2

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…

3mIntermediate19.5k students

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

Previous Lesson
Next Lesson
Constraints and defaults — TypeScript Deep Dive — Vertex