Skip to content
webtype.orgwebtype.org

    ↑↓ move · ⏎ open · esc close

    Operators

    infer

    Declares a variable the compiler fills in by pattern-matching.

    What it is

    Only legal in the extends clause of a conditional type, and only usable in the true branch. Read T extends Promise<infer U> as "does T look like a promise of something, and if so call that something U" — the same shape as destructuring, moved to the type level.

    Examples

    • Unwrap<Promise<string>>
      →string
    • Unwrap<number>
      →number
    • Head<[1, 2, 3]>
      →1

      The same operator against a tuple pattern. infer does not care what shape you are matching.

    Each resolved type above was printed by TypeScript 6.0.3, not written by hand.

    What it does not do

    • It is not usable in the false branch. U does not exist there, because nothing matched and there was nothing to name.
    • It does not pick one when several match. Multiple infer of the same name in one position produce a union, and in argument positions an intersection — which is a trick, not a bug.

    Takeaway

    If you can describe the shape you are looking for, infer will hand you the piece you wanted out of it. Most of the standard library’s cleverness is this one operator.