Trim Right
Less than 1 minuteTC-Medium
Trim Right
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>
: SHow it works:
- Pattern match
Sas${Rest}${Whitespace}— i.e., any string ending with a whitespace character. - If it matches, strip the trailing whitespace and recurse on
Rest. - If it doesn't match (no trailing whitespace), return
Sas-is.
Key Takeaways
TrimRightis the mirror ofTrimLeft— just move the whitespace check to the suffix position.- Template literal inference is greedy from the left, so
${infer Rest}${Whitespace}correctly captures everything before the last whitespace character. - Combining
TrimLeftandTrimRightgives you a fullTrimimplementation.
