Skip to content

Instantly share code, notes, and snippets.

@jspears
Last active February 10, 2022 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jspears/e834631bc764533e027173a872f11711 to your computer and use it in GitHub Desktop.
Save jspears/e834631bc764533e027173a872f11711 to your computer and use it in GitHub Desktop.
TypeScript/Type string utils

Let's face it working with strings in TypeScript types isn't always obvious, so I thought I would write some little utilities to make that easier. These are the ones that come to mind.

type UpperFirst<T> = T extends `${infer First}${infer Rest}` ? `${Capitalize<First>}${Rest}` : T;

type ReplaceAll<T,Word extends string, With extends string> = 
T extends `${infer Left}${Word}${infer Right}` ?
`${Left}${With}${ReplaceAll<Right, Word, With>}` :
T extends `${Word}${infer Right}` 
? `${With}${ReplaceAll<Right, Word, With>}` 
: T extends Word ? With : T;

type ReplaceFirst<T,Word extends string, With extends string> = 
T extends `${infer Left}${Word}${infer Right}` ?
`${Left}${With}${Right}` :
T extends `${Word}${infer Right}` ? 
`${With}${Right}` : T extends Word ? With : T;
 
 
type Reverse<T> =  T extends `${infer First}${infer Rest}` ? `${Reverse<Rest>}${First}` :T ;

type Split<T, D extends string, Ret extends string[] = []> =
 T extends '' ? Ret :
 T extends `${infer Left}${D}${infer Rest}` ? Split<Rest, D, [...Ret, Left]> : 
 [...Ret,T];

type Join<T, D extends string =' ', Ret extends string = ''> = T extends [infer First, ...infer Rest] ?
     First extends string ? Join<Rest, D, Ret extends '' ? First : `${Ret}${D}${First}`>  : Join<Rest,D,Ret> : Ret ; 

type Trim<T> = T extends (` ${infer Value}` | `${infer Value} ` | `${infer Value}\n`) ? Trim<Value> : T;


type T1 = ReplaceAll<'all my friends allways say all', 'all', 'none'>;
type T2 = Split<'split,this,up', ','>;
type T3 = UpperFirst<"hello">;
type T4 = ReplaceFirst<'my first word is first', 'first', 'second'>
type T5 = Reverse<'backwards'>;

playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment