Annotated solution
Published August 6, 2026The solution
type Replace<S extends string, From extends string, To extends string> = From extends '' ? S : S extends `${infer H}${From}${infer T}` ? `${H}${To}${T}` : S
The common wrong answer
type Replace<S extends string, From extends string, To extends string> = S extends `${infer H}${From}${infer T}` ? `${H}${To}${T}` : S
Correct for every input except an empty `From`. The empty string sits between any two characters, so the pattern matches with `H` empty and inserts `To` at the front — `Replace<"abc", "", "x">` becomes `"xabc"`.
Line by line
From extends '' ? SThe guard has to come first. Once the template pattern is reached an empty `From` has already made the match succeed, and there is no way to distinguish it afterwards.
`${infer H}${From}${infer T}`Inference is greedy from the left, so `H` takes the shortest prefix that still lets the rest match. That is precisely why only the *first* occurrence is replaced.
Takeaway
The empty string is the null of template literal types: it matches everywhere and silently breaks patterns that assume a match means something was found.