Simple sample works as expected:
type Data = {
a: number
b: number
}
const data: Data[] = [
{a :1, b: 1},
{a: 2, b: 2}
].sort((el1, el2) => el1.a - el2.a)
sorting works, type is preserved.
But it does not work to array of tuples:
type Data = [number, number]
const data: Data[] = [ // error: Type number[][] is not assignable to type Data[]
[1, 2],
[3, 4]
].sort((a, b) => a[0] - b[0])
And with heterogeneous items it’s even more crazy:
type Data = [number, number]
const data: Data[] = [ // error: Type '(number | boolean)[][]' is not assignable to type 'Data[]'
[1, true],
[3, false]
].sort((a, b) => a[0] - b[0])
// ^? (parameter) a: (number | boolean)[]
Are my types conceptually wrong? Or is it a known limitation and, if yes, is there a workaround?
PS I know .sort()
mutates an array. But since top-level is not a tuple, I’d expect Typescript preserve result type and properly infer element’s type inside of .sort()