ghaiklor / type-challenges-solutions

Solutions for the collection of TypeScript type challenges with explanations
https://ghaiklor.github.io/type-challenges-solutions/
Creative Commons Attribution 4.0 International
470 stars 56 forks source link

type-challenges-solutions/ru/medium-trim #72

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

Trim

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/ru/medium-trim.html

boggddan commented 3 years ago

вот еще один вариант решения

type TrimLeft<S extends string> = S extends ` ${infer T}` | `${infer T} ` ? TrimLeft<T> : S;
type trimed = TrimLeft<'  Hello World  '> // expected to be 'Hello World  '
type trimed2 = TrimLeft<'  Hello World'> // expected to be 'Hello World  '
type trimed3 = TrimLeft<'Hello World  '> // expected to be 'Hello World  '
ghaiklor commented 3 years ago

@boggddan этот даже попроще будет, хороший трюк с объединением 👍🏻

bini1988 commented 2 years ago

Решение через union:

type TrimChars = ' ' | '\n' | '\t';
type Trim<S extends string> = S extends `${TrimChars}${infer R}` | `${infer R}${TrimChars}` ? Trim<R> : S;