#4803Medium

Trim Right

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.

Challenge Instructions: Trim Right

Medium

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

For example:

[object Object]

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<TrimRight<'str'>, 'str'>>,
  Expect<Equal<TrimRight<'str '>, 'str'>>,
  Expect<Equal<TrimRight<'str     '>, 'str'>>,
  Expect<Equal<TrimRight<'     str     '>, '     str'>>,
  Expect<Equal<TrimRight<'   foo bar  \n\t '>, '   foo bar'>>,
  Expect<Equal<TrimRight<''>, ''>>,
  Expect<Equal<TrimRight<'\n\t '>, ''>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Whitespace = ' ' | '\n' | '\t';
 
type TrimRight<S extends string> =
  S extends `${infer Rest}${Whitespace}`
    ? TrimRight<Rest>
    : S;

How it works:

This 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.

Share this challenge

Learn the Concepts