#25170Medium

Replace First

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.

Challenge Instructions: Replace First

Medium

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).

👋 Lifetime-License is leaving on August 10, 2026

Get it now for $29

One-time payment. Lifetime access to all pro challenges.

Loading...

Detailed Explanation

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:

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.

Share this challenge

Learn the Concepts