[Typescript] 25. Medium - Trim Left

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

For example

type trimed = TrimLeft<'  Hello World  '> // expected to be 'Hello World  '

 

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


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

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

 

Simpler way: dirctly use ${SpaceType} instead of ${infer Space}... Space extends...

type SpaceType = ' ' | '\t' | '\n'
type TrimLeft<S extends string> = S extends `${SpaceType}${infer REST}` ? TrimLeft<REST> : S;

 

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