Last active
March 7, 2023 20:49
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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