#35191Medium

Trace

The trace of a square matrix is the sum of the elements on its main diagonal. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a Trace type that extracts the diagonal elements of a square matrix and returns them as a union type, mirroring the mathematical concept of a matrix trace at the type level.

Challenge Instructions: Trace

Medium

The trace of a square matrix is the sum of the elements on its main diagonal. However, it's difficult to calculate the sum with type system. To make things simple, let's return the elements on the main diagonal with union type.

For example:

type Arr = [
[1,2],
[3,4]
]
type Test = Trace<Arr> // expected to be 1 | 4

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

ChallengeSolution
type cases = [
  Expect<Equal<Trace<[[1, 2], [3, 4]]>, 1 | 4>>,
  Expect<Equal<Trace<[[0, 1, 1], [2, 0, 2], [3, 3, 0]]>, 0>>,
  Expect<
    Equal<
      Trace<[['a', 'b', ''], ['c', '', ''], ['d', 'e', 'f']]>,
      'a' | '' | 'f'
    >
  >,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Trace<T extends any[][], I extends any[] = []> =
  I['length'] extends T['length']
    ? never
    : T[I['length']][I['length']] | Trace<T, [...I, 0]>;

How it works:

An alternative approach uses a mapped type over the matrix rows:

type Trace<T extends any[][]> = {
  [K in keyof T]: K extends `${infer N extends number}` ? T[K][N] : never;
}[number];

This maps over each row index K, converts it from a string key to a numeric index N using template literal inference, then accesses T[K][N] to get the diagonal element. The final [number] indexes into the mapped tuple to produce a union of all diagonal values.

This challenge helps you understand recursive type-level iteration and tuple indexing, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge