The Weird Parts of TypeScript 13 exercises

Evolving Types using the `any` type

In this exercise, we're going to explore an advanced technique for working with evolving types using the any type.

Here's some initial code, where selectedId is number and has a passing test that proves it:

let selectedId = 123;
type test = Expect<Equal<typeof selectedId, number>>;

Loading exercise


00:00 In this exercise, we're going to talk about an evolving any, evolving any here you can see we have a let selected ID equals 123. And if we hover over selected ID, we're going to see it's a number. Selected ID can be changed because it's a let, but it can't be changed to a string. Further down, we have selected ID equals 123, which is a string. And this is erroring here. And this is a little annoying, because let's say we want this behavior to happen, we want selected ID to be released.

00:30 There's a couple of potential solutions here, but there's going to be one which is going to knock your socks off, I think, because TypeScript can be pretty clever with these lets. So try to the line of code that we're changing is this one up here, which is let selected ID equals 123.

00:46 If we change this code, perhaps split it out into a couple more lines, you're going to notice that the behavior that we want, which is the type of this thing to evolve over time, is going to be easier. Yeah, I'm going to leave it there, I think. Good luck with this one. This is an interesting solution.