Don't Side-step TypeScript

01/23/2021 , 2m, 56s

Hello everyone So today I'm going to talk about TypeScript and tricking type script versus fixing your code So, you know, the the null non-null assertion thing where you put the exclamation point at the end of something to say, hey type script this isn't going to be no or whatever.

I don't really use that. There's actually two reasons. One of them is because it looks like when you're looking at the code that looks like that's a feature of JavaScript, but it's not and so I don't really like using things that look like they could be a feature of JavaScript but aren't I don't know maybe that's just weird of me.

But the the biggest reason is that most often if TypeScript thinks that this can be null it's most likely that it actually can be no and and you could put that bang there or you can do type assertions or casting and whatever but it's I I don't like telling TypeScript that no this like this won't be this value when it actually could be that value.

So I'm thinking about a specific example that my friend Peter on discord on during office hours today brought up and I was.Live streaming and I was reading a value out of local storage and and then parsing that with JSON down parse. And JSON parts can technically accept anything and then it stringifies it and so you can pass it null it will stringify it to null and the result will be null.

Sorry, it will stringify it to the string of null and then the result of parsing that will be no. And so yeah, you can just pass in no but the typescript definitions for that except specifically a string. It has to be a string that you pass to it. Even though you can technically pass anything and it'll just get stringified automatically.

So,What I did was I did the double question marks, whatever that's called the I can't remember what that operator is called but yeah. So I'd say okay read in the locust storage if that's null then it will just pass in the string of null and then that will result in an old value.

And he suggested that oh why don't you just do a bang on that on the end of that and then that should work just fine just say, you know, hey type script this is not going to be null, but it actually will be it'll just be okay that it'll be null.

And so,But he also suggested you could also just pass it to the string constructor and then that would stringify null and then you could pass it in And I opted for passing it to the string constructor because I don't want to tell TypeScript that this will never be this null value.

What it actually will be in reality. And so it's not just communicating to TypeScript. It's also communicating to the other people who are going to be reading the code. So anyway, I hope that's sort of useful and train of thought try not to convince. TypeScript that something will not be of a certain type what it actually could be.

Hope you're having an awesome day, we'll see you all next time.