This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for TypeScript puzzle on BFE.dev
34. implement Repeat<T, C>

Here's one possible solution using recursion and conditional types:

type Repeat<T, C extends number> = C extends 0 ? [] : [T, ...Repeat<T, C-1>];

Explanation:

  • T is the type to repeat.
  • C is the number of times to repeat it. We use a conditional type to detect the special case of C being zero, which means the result should be an empty tuple.
  • We define Repeat to be a tuple: the first element is always of type T, and the rest is obtained by recursively calling Repeat with T and C-1.
  • The ... syntax is used to spread the result of the recursive call, so that it becomes part of the tuple.

Let's test it with the examples from the prompt:

type A = Repeat<number, 3>; // [number, number, number]
type B = Repeat<string, 2>; // [string, string]
type C = Repeat<1, 1>; // [1, 1]
type D = Repeat<0, 0>; // []

All of them are type-checked correctly by TypeScript. Note that C being negative is not a valid input according to the prompt, so the behavior in that case is not specified. This implementation assumes that negative numbers are simply treated as zero.