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).
type cases = [
Expect<Equal<ReplaceFirst<[1, 2, 3], 3, 4>, [1, 2, 4]>>,
Expect<Equal<ReplaceFirst<['A', 'B', 'C'], 'C', 'D'>, ['A', 'B', 'D']>>,
Expect<
Equal<ReplaceFirst<[true, true, true], true, false>, [false, true, true]>
>,
Expect<
Equal<
ReplaceFirst<[string, boolean, number], boolean, string>,
[string, string, number]
>
>,
Expect<Equal<ReplaceFirst<[1, 'two', 3], string, 2>, [1, 2, 3]>>,
Expect<
Equal<
ReplaceFirst<['six', 'eight', 'ten'], 'eleven', 'twelve'>,
['six', 'eight', 'ten']
>
>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.