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 snippetCopytypescripttype trimed = Trim<' Hello World '> // expected to be 'Hello World'
Test Cases
code snippetCopytypescriptimport { 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 snippetCopytypescripttype Trim<S extends string> = S extends `${' ' | '\n' | '\t'}${infer P}` | `${infer P}${' ' | '\n' | '\t'}`
? Trim<P>
: S