Explainers

TypeScript infer: The Compiler Reads Your String

Published
Duration
Language
English

Watch on YouTube ↗

Summary

TypeScript can pull a type out of another type. That is infer. This short explainer starts with Unwrap, which looks inside a Promise of string and returns string, then uses the same idea on strings. IsParam asks whether a string starts with a colon: :id becomes id, and users becomes never. extends is the pattern; infer is the hole TypeScript fills in. Params then walks a route slash by slash, keeps only the segments that start with a colon, and builds a union: from /users/:id/posts/:postId the result is exactly id or postId. A route function takes that path and types the params object from it. Pass id and postId, and it compiles. Pass postId where the path only has id, and TypeScript reports that postId does not exist on a record that expects id.

Every snippet was checked with tsc strict mode on TypeScript 7.0.2 and 5.9.3.

Chapters

  1. 0:00 infer and Unwrap
  2. 0:16 A string that starts with a colon
  3. 0:33 Walking a route with Params
  4. 0:48 The compiler reads your string

Transcript

Text of the video's narration.

TypeScript can pull a type out of another type. That is infer. Unwrap looks inside a Promise of string and returns string. A plain number is left alone. extends is the pattern; infer is the hole TypeScript fills in. The same idea works on strings, and this is the useful part.

IsParam asks whether a string starts with a colon. The pattern is a colon, then a hole named Name.:id fills that hole with id. users matches nothing, so you get never. Now give it a whole route. Params walks the path slash by slash, keeps only the segments that start with a colon, and joins them into a union.

From /users/:id/posts/:postId, you get exactly id or postId. Here is the payoff. A route function takes your path and types the params object from it. Pass id and postId, and it compiles. Pass postId where the path only has id, and it does not compile.

Pass an empty object, and TypeScript tells you id is missing. The compiler reads your string.

Sources

Credits and notes

  • Narrated with Phonon; motion in Remotion.

More in this series · Explainers