Go Back

Refer: Medium - Trim

Describe

Implement Trim<T> which takes an exact string type and returns a new string with the whitespace from both ends removed.

For example

code snippetCopytypescript
type trimed = Trim<' Hello World '> // expected to be 'Hello World'

Test Cases

code snippetCopytypescript
import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<Trim<'str'>, 'str'>>, Expect<Equal<Trim<' str'>, 'str'>>, Expect<Equal<Trim<' str'>, 'str'>>, Expect<Equal<Trim<'str '>, 'str'>>, Expect<Equal<Trim<' str '>, 'str'>>, Expect<Equal<Trim<' \n\t foo bar \t'>, 'foo bar'>>, ]

Solution

code snippetCopytypescript
type Trim<S extends string> = S extends `${' ' | '\n' | '\t'}${infer P}` | `${infer P}${' ' | '\n' | '\t'}` ? Trim<P> : S