Reputation: 379
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
Upvotes: 4
Views: 1823
Reputation: 185117
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.
Upvotes: 1
Reputation: 371
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.
Upvotes: 7