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

Loading...

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

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount