#21104Medium

FindAll

Given a pattern string P and a text string T, implement the type FindAll<T, P> that returns an Array that contains all indices (0-indexed) from T where P matches. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement FindAll<T, P> which takes a text string T and a pattern string P, and returns an array of all 0-indexed positions in T where P is found as a substring.

Challenge Instructions: FindAll

Medium

Given a pattern string P and a text string T, implement the type FindAll<T, P> that returns an Array that contains all indices (0-indexed) from T where P matches.

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<
    Equal<FindAll<'Collection of TypeScript type challenges', 'Type'>, [14]>
  >,
  Expect<
    Equal<FindAll<'Collection of TypeScript type challenges', 'pe'>, [16, 27]>
  >,
  Expect<Equal<FindAll<'Collection of TypeScript type challenges', ''>, []>>,
  Expect<Equal<FindAll<'', 'Type'>, []>>,
  Expect<Equal<FindAll<'', ''>, []>>,
  Expect<Equal<FindAll<'AAAA', 'A'>, [0, 1, 2, 3]>>,
  Expect<Equal<FindAll<'AAAA', 'AA'>, [0, 1, 2]>>,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

We iterate through the string one character at a time, checking at each position whether the pattern matches at that index. We use a counter tuple to track the current index.

type FindAll<
  T extends string,
  P extends string,
  Index extends any[] = []
> = P extends ''
  ? []
  : T extends `${infer _First}${infer Rest}`
    ? T extends `${P}${string}`
      ? [Index['length'], ...FindAll<Rest, P, [...Index, 1]>]
      : FindAll<Rest, P, [...Index, 1]>
    : []

How it works:

This challenge helps you understand template literal type pattern matching with index tracking and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge