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

ChallengeSolution
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']
    >
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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