Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript [number, number] vs number[]

Tags:

typescript

Can someone help me understand why I get a type error with the following code:

function sumOfTwoNumbersInArray(a: [number, number]) {
    return a[0] + a[1];
}

sumOfTwoNumbersInArray([1, 2]); // Works

let foo = [1, 2];
sumOfTwoNumbersInArray(foo); // Error

The error is:

Argument of type 'number[]' is not assignable to parameter of type '[number, number]'.

Type 'number[]' is missing the following properties from type '[number, number]': 0, 1

like image 583
Sean Avatar asked Oct 17 '25 02:10

Sean


2 Answers

The parameter a in sumOfTwoNumbersInArray is a tuple. It is not the same as number[].

The following works okay because all variables are basic arrays

function sumOfTwoNumbersInArray(a: number[]) { // parameter declared as array
  return a[0] + a[1];
}

let foo = [1, 2]; // initialization defaults to array

sumOfTwoNumbersInArray(foo); // no error.

As Rafael mentioned, explicitly defining foo as a tuple works fine as well.

function sumOfTwoNumbersInArray(a: [number, number]) { // parameter declared as a tuple
  return a[0] + a[1];
}

let foo: [number, number] = [1, 2]; // variable explicitely defined as a tuple

sumOfTwoNumbersInArray(foo); // no error.
like image 188
Venkey Avatar answered Oct 18 '25 20:10

Venkey


In most cases when people create an array they want it to have dynamic size, so the type is number[].

In newer TS you should be able to do this to get constant size typing:

let foo = [1, 2] as const;

This may prevent changing the array, though. So if you want that you need to explicitly use [number, number] as type annotation.

like image 23
H.B. Avatar answered Oct 18 '25 20:10

H.B.