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 cases = [
Expect<Equal<Transpose<[]>, []>>,
Expect<Equal<Transpose<[[1]]>, [[1]]>>,
Expect<Equal<Transpose<[[1, 2]]>, [[1], [2]]>>,
Expect<Equal<Transpose<[[1, 2], [3, 4]]>, [[1, 3], [2, 4]]>>,
Expect<Equal<Transpose<[[1, 2, 3], [4, 5, 6]]>, [[1, 4], [2, 5], [3, 6]]>>,
Expect<Equal<Transpose<[[1, 4], [2, 5], [3, 6]]>, [[1, 2, 3], [4, 5, 6]]>>,
Expect<
Equal<
Transpose<[[1, 2, 3], [4, 5, 6], [7, 8, 9]]>,
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>
>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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.