The Weird Parts of TypeScript 13 exercises
solution

The Evolving `any` Type

The best solution here is to turn selectedId into an "evolving any."

First, declare selectedId on its own line:


let selectedId;

Hovering over selectedId shows us that it is inferred as any:


// hovering over `selectedId`
let selectedId: any;

Now we c

Loading solution

Transcript

00:00 Okay, the solution here is really interesting, and the solution is to turn SelectedID into what's called an Evolving Any. Now, if we split this up into two lines now, if we declare SelectedID as just a variable up here, without any assignment to it, what we can see is it

00:18 gets inferred as Any. Now, we can say SelectedID equals 1, 2, 3, and suddenly everything starts working. Now, the reason this is happening is when you declare a let without any type annotation, TypeScript infers it as an Any, but it's not an Any like we've seen before.

00:37 It doesn't actually disable any type checking on it. It's actually what's called an Evolving Any. So, this ID basically waits for something to be assigned to it, and when it gets assigned to it, it realizes, okay, that's the type I'm supposed to be. So, now we can see that

00:53 SelectedID in this position here, when it's being assigned, is still Any. But later, SelectedID.toExponential, we can see that SelectedID is a number. What? Then further down the line, it doesn't forget

01:08 that it can be evolving here. It understands, okay, so because you started me as an Evolving Any, I can evolve to something else. And so, we can actually assign different stuff to it, and we can assign strings to it too. So, now SelectedID.toExponential is no longer

01:25 available here, whereas we now have all of the string methods. So, toLocaleUpperCase is available to us. This is a really powerful pattern because it lets us do really dynamic things that we can do in JavaScript, and TypeScript is smart enough to keep up. Incredibly cool Evolving Anys.