AI Hints
Home›TypeScript Tutorial›Types from Types
TypeScript · Lesson 69 of 120

infer

Pull a type out.

⏱ 2 min read▶ Video at 52:52🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Inside a conditional type, infer captures part of a type into a new name. It's how ReturnType is built. Let's write our own unwrapping helpers.

infer
From the video: infer
  • Capture a part
  • infer
  • Build your own helpers

Unwrapping types

Item of looks inside an array, and infers its item type. Unwrap looks inside a promise, and infers what it resolves to. Run it. Both types come out correctly.

app.tstypescript
type ItemOf<T> = T extends (infer I)[] ? I : never;
type Unwrap<T> = T extends Promise<infer V> ? V : T;

type Store = ItemOf<string[]>;                    // string
type Total = Unwrap<Promise<number>>;             // number

const store: Store = "Leeds";
const total: Total = 65;
console.log(store, total);
Output
Leeds 65

Summary

Infer captures part of a type inside a conditional type. Next, template literal types.

Key takeaways
  • infer I
  • ItemOf<T>
  • Unwrap<T>
Next up: Template Literal Types — types from strings