TypeScript can infer variable types from initial values and return statements. Even still, we may not know exactly what type inference to expect when dealing with arrays. For example:
let examAnswers= [true, false, false];
What is the type of
examAnswers? It seems it could equally well be
[boolean, boolean, boolean]. In reality, it is always the first of these, since this is the less restrictive type. This enables us to expand the array:
examAnswers = true; // No type error.
Since tuples have fixed lengths, we wouldn’t be able to add additional boolean elements to a tuple:
let tupleOfExamAnswers: [boolean, boolean, boolean] = [true, false, false]; tupleOfExamAnswers = true; // Type error! The tuple only has 3 elements.
We also get the same kind of type inference when we use the
let tup: [number, number, number] = [1,2,3]; let concatResult = tup.concat([4,5,6]); // concatResult has the value [1,2,3,4,5,6].
In the code above, TypeScript infers the variable
concatResult as an array of numbers, not a tuple.
The takeaway here is that type inference returns arrays. When we want tuples, we need to use explicit type annotations.
Let’s do a tricky example. We have defined the tuple
dogTup in the code editor. Your challenge is to define a variable
myArr of the type
Not so fast! The hard part is that you are not allowed to use the word
Array, or the characters
]. Use the
.concat() method and your wits to solve the problem.
You figured it out! Now demonstrate that
myArr is an array rather than a tuple by adding the code
myArr = 'not a dog' and running
myArr were a tuple, accessing element 50 would be impossible!