[Typescript] 26. Medium - Trim

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

For example

type trimmed = Trim<'  Hello World  '> // expected to be 'Hello World'

 

/* _____________ Your Code Here _____________ */
type SpaceType = ' ' | '\t' | '\n'
type Trim<S extends string> = S extends `${SpaceType}${infer REST}` 
  ? Trim<REST>
  : S extends `${infer REST}${SpaceType}`
    ? Trim<REST>
    : S;

/* _____________ Test Cases _____________ */
import type { 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'>>,
  Expect<Equal<Trim<''>, ''>>,
  Expect<Equal<Trim<' \n\t '>, ''>>,
]

 

[Notice]: Can use ${SpaceType} directly without infer

posted @ 2022-09-11 21:28  Zhentiw  阅读(11)  评论(0编辑  收藏  举报