Skip to content
webtype.orgwebtype.org

    ↑↓ move · ⏎ open · esc close

    No. 256 · September 8, 2026 · Moderate

    Invert

    Implement Invert<T> so the values of T become the keys and the keys become the values.

    01

    Try the puzzle yourself

    Par 3

    Puzzle

    invert-object.ts
    Stroke 1 of 3Not run yet

    Replace ??? — your solution is checked against the cases below. Tab indents; press Escape then Tab to move focus out.

    Checks

    3
    • Invert<{ a: 'x'; b: 'y' }>—
      → { x: 'a'; y: 'b' }
    • Invert<{ a: 'x' }>—
      → { x: 'a' }
    • Invert<{}>—
      → {}

    How a check is judged Exact type equality, not assignability — an intersection is not the same as the flattened object.

    How everyone did

    Fewer than 5 people have solved this one so far. The distribution appears once there is enough of a sample to mean anything.

    Short game

    Fewest characters

    No public scores yet.

    Archive
    02

    Annotated solution

    Published September 9, 2026

    The solution

    type Invert<T extends Record<string, string>> = { [K in keyof T as T[K]]: K }

    The common wrong answer

    type Invert<T extends Record<string, string>> = { [K in keyof T as T[K]]: T[K] }

    Half the swap. The key is renamed to the old value, which is right, and then the value is set to the old value as well — producing { x: "x" } where the check wants { x: "a" }. Renaming a key does not move the old key anywhere; if you want it, you have to put it in the value clause yourself.

    Line by line

    1. as T[K]

      The new key is the old value. as accepts any expression that produces a key type, and an indexed access is one.

    2. : K

      And the new value is the old key, still in scope, still a literal. The two clauses are independent — which is what makes a clean swap possible in one line.

    Takeaway

    A mapped type makes two separate decisions per key: what it is called, and what it holds. Most mapped-type bugs are one of those two answers accidentally reused for the other.

    Uses