Yuzhe's Blog

yuzhes

Trim Right

Trim Right

Problem Link

Problem

Implement TrimRight<T> which takes an exact string type and returns a new string with the whitespace ending removed.

type Trimed = TrimRight<'   Hello World    '> // '   Hello World'

Solution

Approach: Recursive Suffix Stripping

Check if the string ends with a whitespace character; if so, strip it and recurse.

type Whitespace = ' ' | '\n' | '\t'

type TrimRight<S extends string> =
  S extends `${infer Rest}${Whitespace}`
    ? TrimRight<Rest>
    : S

How it works:

  1. Pattern match S as ${Rest}${Whitespace} — i.e., any string ending with a whitespace character.
  2. If it matches, strip the trailing whitespace and recurse on Rest.
  3. If it doesn’t match (no trailing whitespace), return S as-is.

Key Takeaways