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/en/medium-replaceall #181

Open utterances-bot opened 2 years ago

utterances-bot commented 2 years ago

ReplaceAll

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/en/medium-replaceall.html

wdcryer commented 2 years ago

I came up with a slightly different solution that I think is a bit simpler, and passes all the current tests. It seems like rather than storing a separate Before parameter, you can use ${infer L}${From} and append ${ReplaceAll<R, From, To>} to just replace parts of the remaining string.

type ReplaceAll<S extends string, From extends string, To extends string> = From extends ''
? S
: S extends `${infer Before}${From}${infer After}` 
?`${Before}${To}${ReplaceAll<After, From, To>}`
: S

Thanks so much for this amazing site! I didn't even know how to use infer until reading some of your explanations.

JanessaTech commented 1 week ago

mine is similar to @wdcryer . Thanks everyone