BRIEFS logo BRIEFS

Don't Trick TypeScript

03/08/2021 , 2m, 58s

Hey friends So today I was writing a blog post as I often do and I wanted to ask a question of some TypeScript folks always in the Tit script community and my question sparked a long discussion kind of argument between people about whether a assertion function is tricking the compiler if you're not throwing an error in the function.

So let me explain I actually recently wrote a blog post about the different function syntaxes that you have in TypeScript and one of the things that you can do is make an assertion.Function and basically what that does is you say, hey type script this function asserts that the given argument is of a certain type.

And so therefore you can do some type narrowing by calling that function. So say you've got a an array and you want to filter out anything that's not a number then you can write a filter function that asserts that things are or maybe rather not filtering out a number but you want to make sure that everything's a number and so if one of them isn't a number then you want to throw an error or something like that.

And so you can make a function that asserts that it's input is a number and if it's not then that won't be accepted and so what some people are arguing is it's totally fine to not actually throughout the error and just make an assertion function that that says that the types cannot be anything but a number.

But this one an individual is saying no that's tricking the compiler you need to make sure that you actually do throw an error if the type is not a number. So my opinion is I agree with that. I think that you should not be doing things with theCompiler that are basically saying hey type script my code does this but your code doesn't actually do that.

You're just tricking the compiler into thinking that your code does that so that you can make the compiler do what you want it to do. So basically, I want to make sure that the code that I end up shipping to the browser operates in the way that I'm telling TypeScript it's going to operate and if you're so like if you trust so much the compiler to make sure that your types are all correct and everything then you shouldn't ever run into the situation.

When you actually do throw because your type should be correct But if something weird happens, then you actually do want to have that that error thrown because unexpected things could happen down the line which could make things even worse. So I would really recommend that you don't try to trick the compiler when you tell type script a thing as of a certain type it better be of that type when you're making an assertion function, you better be doing some assertions.

I think that's important though. Anyway, I hope that's interesting. Have a wonderful awesome typescript.