The Weird Parts of TypeScript 13 exercises
explainer

The Evolving `any` and Arrays

The evolving any is available on Arrays as well. When you declare an Array without any specific annotation, you can push various types of elements to it.

For instance, you have an unannotated Array:


const arr = [];

If we push a number into the array, it becomes an Array of tha

Loading explainer

Transcript

00:00 The Evolving Any is also available on Arrays. When you declare an Array and you basically just leave it unannotated here, then what can happen is we have our Array and we can push things to it. And when we push things to that Array, then it actually ends up the Array. If we say Array, let's grab the first one and let's say we get our two exponential back.

00:20 Now it's an Array of that thing. So cool. This is like a special case in TypeScript and Evolving Any Array. And then later we can push other things to it and it will be a type of Array, String or Number. So now it's a little, you know, a little different to how we had it before, which was this instead of just being sort of overridden by the type.

00:41 Now, in theory, this Array would be first it would contain a 1 and then it would contain ABC. So it would be an Array of String or Number. So this is another example of how Evolving Any is a kind of built into TypeScript to let you do really smart things with them. And bear in mind, too, that if you were to just give a type annotation to this,

01:00 let's say we just say as a String Array, for instance, or let's say a String or Number Array, then you get some similar behavior and still be able to push and push different things to it. But at this moment, when we're checking, when we've just pushed a single number to it, it would actually be slightly incorrect here because it would be assuming

01:21 that there were strings in the Array when there actually weren't. So, again, TypeScript is so smart in the way that it just picks up on what you're doing and picks up on the behavior that you're pushing to these Evolving Any's and Evolving Any Arrays and means that, you know, this line of code without adding any type annotations is about as smart as it possibly could be. So cool.