Implement `TrimRight<T>` which takes an exact string type and returns a new string with the whitespace ending removed. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a TrimRight type that removes trailing whitespace characters from a string type, similar to JavaScript's trimEnd() but operating entirely at the type level.
Implement TrimRight<T> which takes an exact string type and returns a new string with the whitespace ending removed.
For example:
type Trimmed = TrimRight<' Hello World '> // expected to be ' Hello World'Change the following code to make the test cases pass (no type check errors).
type Whitespace = ' ' | '\n' | '\t';
type TrimRight<S extends string> =
S extends `${infer Rest}${Whitespace}`
? TrimRight<Rest>
: S;How it works:
Whitespace union type defines the three characters we consider whitespace: space, newline, and tabTrimRight uses a conditional type with template literal inference to check if the string S ends with any whitespace character${infer Rest}${Whitespace} captures everything before the trailing whitespace character as Rest, and the type recurses on Rest to strip the next trailing characterThis challenge helps you understand template literal types and recursive string manipulation, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount