Essential Types And Notations 20 exercises

The Dangers of Using "any"

In this case, using any did not help us at all. In fact, any annotations seem to actually turn off type checking!

With any, we're free to do anything we want to the variable, and TypeScript will not prevent it.

Using any also disables useful features like autocompletion, which can help yo

Loading solution


00:00 Okay, if you managed to find the solution, well done. You would have noticed that E really did not help us at all. There's any annotations seem to actually turn off type checking. You can see that actually, we're actually free to do anything we want to, to this any and TypeScript will not prevent it. If this was like an object

00:19 with like a prevent default function on it, defaults like this void, then we would actually have some autocomplete on it. So prevent default here, but any turns off autocomplete. And so what this means is in order to fix this error, we have to treat it like JavaScript.

00:37 And remember, treat it like JavaScript. Think about typos, think about stupid mistakes you could have made that TypeScript tends to prevent., target, I don't know what stupid pronunciation I would use there, but if we change this to, then it works. So what has happened here?

00:57 Well, E.typedAsAny has meant that we've turned off type checking on that E and it means that it's now assignable to anything and anything is assignable to it. So if we were to find a more sensible type for this, let's say this E that we get on the submit here is actually typed as submit event. We'll talk about where this submit event comes from,

01:15 but you can actually just type it as submit event here. Oh dear, but this is leading to some sort of error here. Arguments of type event target null is not assignable to parameter of type HTML form element. Hmm, there's something weird going on here. And so you would have to do some fairly advanced stuff in order to get this working.

01:35 And so someone, I guess me, on this code has just said, okay, fine, to get this working, we're just gonna make an any here. And that any is sort of okay in this situation. It makes the type error go away, but of course it exposes us to bugs further down the line. We're gonna talk about this a lot more later,

01:53 but I wanted to give you like an early insight into any, some problems it can cause, and because it's present in a few different global JavaScript and TypeScript APIs. There you go, any.