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.
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 | 4Change the following code to make the test cases pass (no type check errors).
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:
I that starts empty and grows by one element on each recursive step, allowing us to track the current indexI['length'] serves as the index into both the row and column of the matrix, extracting T[I['length']][I['length']] -- the diagonal element|), collecting all diagonal elements togetherI['length'] equals T['length'] (the number of rows), returning never to terminate the recursion without adding to the unionAn 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount