Implement the type ReplaceFirst<T, S, R> which will replace the first occurrence of S in a tuple T with R. If no such S exists in T, the result should be T. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement ReplaceFirst<T, S, R> which replaces the first occurrence of S in a tuple T with R, returning the original tuple if no match is found.
Implement the type ReplaceFirst<T, S, R> which will replace the first occurrence of S in a tuple T with R. If no such S exists in T, the result should be T.
Change the following code to make the test cases pass (no type check errors).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
type ReplaceFirst<T extends readonly unknown[], S, R> =
T extends [infer F, ...infer Rest]
? F extends S
? [R, ...Rest]
: [F, ...ReplaceFirst<Rest, S, R>]
: []How it works:
infer to destructure the tuple into its first element F and the remaining elements Rest.F extends S (matches the search type), we return a new tuple with R replacing F, followed by the unmodified Rest. This ensures only the first occurrence is replaced.F does not match S, we keep F as-is and recursively apply ReplaceFirst to the Rest of the tuple.T extends [infer F, ...infer Rest] fails when the tuple is empty, returning [] and stopping the recursion.This challenge helps you understand recursive tuple manipulation and conditional type inference and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.