type Point = [number, number]
type Points = Array<Point>
const ok: Points = [[0, 0]]
const fail: Points = [0].map(() => [0, 0])
Type 'number[][]' is not assignable to type '[number, number][]'.
Any ideas?
type Point = [number, number]
type Points = Array<Point>
const ok: Points = [[0, 0]]
const fail: Points = [0].map(() => [0, 0])
Type 'number[][]' is not assignable to type '[number, number][]'.
Any ideas?
It's because of how map is typed.
The "official" definition is:
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
If you don't specify U then default U[] will be [] (same as Array).
The problem is that [number, number] is a subset of Array AND map without specifying U would mean the return type will be Array.
The two types not being compatible, you get that error.
Solution is to specify what map is allowed to return:
const okToo: Points = [0].map<Point>(() => [0, 0])
On the other hand I'd expect this to fail too:
const notOk: Points = [0].map<Point>(() => [0, 0, 0])
but on TypeScript 2.6.1 it's allowed. It's an error in 3.3 though, which is really nice.
[0, 0, 0] is an error too.
const fail: Points = [0].map(() => <Point>[0, 0])Playgroundconst fail: Points = [0].map<Point>(() => [0, 0])Otherwise, map cannot exactly guess what the return type will be, since it's dynamic. typescriptlang.org/play/…JSXenvironment? @adigaPointis a component?