Skip to content
webtype.orgwebtype.org

    ↑↓ move · ⏎ open · esc close

    No. 260 · September 12, 2026 · Hard

    How long is it

    Implement StrLength<S> so it produces the number of characters in the string literal S.

    01

    Try the puzzle yourself

    Par 4

    Puzzle

    string-length.ts
    Stroke 1 of 4Not run yet

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

    Checks

    3
    • StrLength<'hello'>—
      → 5
    • StrLength<''>—
      → 0
    • StrLength<'ab'>—
      → 2

    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 13, 2026

    The solution

    type StrLength<S extends string, R extends unknown[] = []> =
      S extends `${string}${infer Rest}` ? StrLength<Rest, [...R, unknown]> : R['length']

    The common wrong answer

    type StrLength<S extends string, R extends unknown[] = []> = S['length']

    A string type does have a length, and it is number — the general one, not 5. Only tuples carry their length as a literal type. This is the reason nearly every counting type in TypeScript is written with a tuple accumulator that nobody ever reads the contents of.

    Line by line

    1. `${string}${infer Rest}`

      The first placeholder is string rather than infer because the character itself does not matter — only that there was one.

    2. [...R, unknown]

      The accumulator is a tally. Its element type is irrelevant; unknown is chosen precisely because nothing will ever look inside it.

    3. R['length']

      And here the tally is cashed in. Because R is a tuple, its length is the literal 5, which is what the check is asking for.

    Takeaway

    Numbers at the type level are tuple lengths. Any time you need to count something, the answer is a tuple you grow and then ask for its length.

    Uses