Is it possible to define a type NumMax<x, y> in Typescript that takes the maximum of two types, such that NumMax<z, z> is assignable to z? The following definition does not work:
export type NumMax<x extends number, y extends number> =
[x, y] extends [0, 0] ? 0
: [x, y] extends [0, 1] ? 1
: [x, y] extends [0, 2] ? 2
: [x, y] extends [0, 3] ? 3
: [x, y] extends [1, 0] ? 1
: [x, y] extends [1, 1] ? 1
: [x, y] extends [1, 2] ? 2
: [x, y] extends [1, 3] ? 3
: [x, y] extends [2, 0] ? 2
: [x, y] extends [2, 1] ? 2
: [x, y] extends [2, 2] ? 2
: [x, y] extends [2, 3] ? 3
: [x, y] extends [3, 0] ? 3
: [x, y] extends [3, 1] ? 3
: [x, y] extends [3, 2] ? 3
: [x, y] extends [3, 3] ? 3
: x;
function func1<x extends number, y extends number>(xx: x, yy: y): NumMax<x, y> {
return null as any; // ... unimportant code ...
}
function func2<z extends number>(z1: z, z2: z): z {
return func1(z1, z2); // ERROR: Type 'NumMax<z, z>' is not assignable to type 'z'
}
Thank you!
Playground: https://tsplay.dev/WKvjpm
Making the
Maxtype is relatively simple if you know what to do:Hovewer, if you write your second function as is, you'll rul into a bug:
To avoid it, disable inferense of one of arguments
edit: here's a variant that works with number unions (but its laggy):