108 - Trim

Author: VarunMendreCreated Sep 16, 2026Updated Sep 16, 2026
Labelsansweren108
type Space = ' ' | '\t' | '\n'

type Trim<S extends string> =
    S extends `${Space}${infer Rest}` | `${infer Rest}${Space}`
        ? Trim<Rest>
        : S;


/*
Example:

type Result = Trim<'  hello  '>


Trim<'  hello  '>
-> S: '  hello  '
-> matches `${Space}${infer Rest}`
-> Space: ' '
-> Rest: ' hello  '
-> Trim<' hello  '>


Trim<' hello  '>
-> S: ' hello  '
-> matches `${Space}${infer Rest}`
-> Space: ' '
-> Rest: 'hello  '
-> Trim<'hello  '>


Trim<'hello  '>
-> S: 'hello  '
-> does NOT start with Space
-> but matches `${infer Rest}${Space}`
-> Rest: 'hello '
-> Space: ' '
-> Trim<'hello '>


Trim<'hello '>
-> S: 'hello '
-> matches `${infer Rest}${Space}`
-> Rest: 'hello'
-> Space: ' '
-> Trim<'hello'>


Trim<'hello'>
-> S: 'hello'
-> does NOT start with:
   ' ' | '\t' | '\n'

-> does NOT end with:
   ' ' | '\t' | '\n'

-> condition is false
-> return S
-> 'hello'


Final Result:
'hello'
*/

Source: type-challenges/type-challenges