The transpose of a matrix is an operator which flips a matrix over its diagonal; that is, it switches the row and column indices of the matrix A by producing another matrix, often denoted by A<sup>T</sup>. Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Transpose type that flips a matrix over its diagonal, swapping row and column indices to produce the transposed matrix entirely at the type level.
The transpose of a matrix is an operator which flips a matrix over its diagonal; that is, it switches the row and column indices of the matrix A by producing another matrix, often denoted by AT.
type Matrix = Transpose <[[1]]>; // expected to be [[1]]
type Matrix1 = Transpose <[[1, 2], [3, 4]]>; // expected to be [[1, 3], [2, 4]]
type Matrix2 = Transpose <[[1, 2, 3], [4, 5, 6]]>; // expected to be [[1, 4], [2, 5], [3, 6]]Change the following code to make the test cases pass (no type check errors).
type Transpose<M extends unknown[][]> =
M extends []
? []
: M[0] extends []
? []
: [
{ [K in keyof M]: M[K] extends [infer F, ...any[]] ? F : never }
& unknown[],
...Transpose<
{ [K in keyof M]: M[K] extends [any, ...infer R] ? R : never }
& unknown[][]
>,
];How it works:
M extends []) and rows that have been fully consumed (M[0] extends []), both returning an empty tuple{ [K in keyof M]: M[K] extends [infer F, ...any[]] ? F : never }unknown[] ensures TypeScript treats the mapped type result as a proper array/tupleM[K] extends [any, ...infer R] ? R : neverThis challenge helps you understand recursive mapped types over tuples and matrix manipulation at the type level, 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