Skip to content
dreamcode
dreamcode
Map
infer
Lesson 21 of 26
+15 XP on finish
TS EXPERTChapter 4 · TS Expert

Inferring Types with infer

Inside a conditional type, infer declares a type variable that TypeScript fills in from the match. T extends Promise<infer V> ? V : T extracts what a promise resolves to, and F extends (...args: any[]) => infer R ? R : never extracts a function's return type. The built-in helpers ReturnType and Awaited are written exactly this way.

Worked example

How it reads

  • infer V captures whatever sits inside Promise<...>
  • Result<typeof makeStar> derives the Star type from the function itself
  • When the pattern does not match, the false branch is used
Cloud tip: Reach for infer when you want a type that is buried inside another one; it keeps derived types in sync with their source.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Rewrite FirstArg with infer so it extracts the type of a function's first parameter. The const arg line should still type-check. Then log greet(arg, 2): NovaNova.

Press Run to check your work.