Skip to content

Instantly share code, notes, and snippets.

@btoo
Last active March 7, 2023 20:49
Show Gist options
  • Save btoo/74dd9a13cb2597bc9ef50860b4893a5f to your computer and use it in GitHub Desktop.
Save btoo/74dd9a13cb2597bc9ef50860b4893a5f to your computer and use it in GitHub Desktop.
TypeScript type-safe string replace and replaceAll (doesn't support regex) using template literal types (note: this is just a proof of concept and shouldnt be taken seriously)
type Replace<
T extends string,
Match extends string,
Replacement extends string
> = T extends `${infer Prefix}${Match}${infer Postfix}`
? `${Prefix}${Replacement}${Postfix}`
: never;
type ReplaceAll<
T extends string,
Match extends string,
Replacement extends string
> = T extends `${infer Prefix}${Match}${infer Postfix}`
? `${Prefix}${Replacement}${ReplaceAll<Postfix, Match, Replacement>}`
: T;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment