1
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?

Playground

5
  • 2
    This works though const fail: Points = [0].map(() => <Point>[0, 0]) Playground Commented Feb 28, 2019 at 13:45
  • I think you need to explicitly define the map return type: const 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/… Commented Feb 28, 2019 at 13:46
  • And how do I make that work in a JSX environment? @adiga Commented Feb 28, 2019 at 13:48
  • Ah, compiler thinks Point is a component? Commented Feb 28, 2019 at 13:51
  • Yea, but briosheje’s suggestion works. Thanks anyway. You should make that an answer @briosheje Commented Feb 28, 2019 at 13:52

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Courtesy playground: typescriptlang.org/play/…
@briosheje thanks! Question though: how do I use that to see the compile errors?
whenever you type something wrong, you just need to hightlight the row and it will show the error, like the original playground the OP provided: prntscr.com/mrcywk (playground here: typescriptlang.org/play/…)
Cool! And it looks like in TS3.3 [0, 0, 0] is an error too.
Well, I guess it should be an error, since you're explicitly defining the return type (which must be of type "Point"). It's quite strange that it's allowed in 2.6.1, to me. Interesting :P.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.