Fixing Typescript error: Type ‘(number | [number, number])[]’ is not assignable to type ‘number[]’

If you try to assign an array you create to another array in Typescript, you can get an error like so:

let range: number[];
range = [
  brush.extent()[0], 
  brush.extent()[1]
];

E.g.:

(91,9): error TS2322: Type '(number | [number, number])[]' is not assignable to type 'number[]'.
  Type 'number | [number, number]' is not assignable to type 'number'.
    Type '[number, number]' is not assignable to type 'number'.

This is because the output of the type you’re assigning from is ambiguous (I’m using D3).

You can convince yourself of this by doing this:

range = [1, 2];

One way to fix this is to use the full type definition, if this helps you:

let range: [number, number] | [[number, number], [number, number]];

You can also fix this by adding type guards around the assignment:

       
const extent = brush.extent();
let first = extent[0];    
let second = extent[1];
if (typeof first === 'number' && typeof second === 'number') {          
  range = [first, second];
}    

This shows some unusual magic in Typescript – the type guard causes an implicit resolution of the type.