Show notes
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 scriptcommunity and my question sparked a long discussion kind of argumentbetween people about whether a assertion function is tricking the compilerif 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 thatyou can do is make an assertion.Function and basically what that does isyou say, hey type script this function asserts that the given argument isof 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 nota number then you can write a filter function that asserts that things areor maybe rather not filtering out a number but you want to make sure thateverything's a number and so if one of them isn't a number then you want tothrow 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 arguingis it's totally fine to not actually throughout the error and just make anassertion function that that says that the types cannot be anything but anumber.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 anumber. So my opinion is I agree with that. I think that you should not bedoing things with theCompiler that are basically saying hey type script mycode 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, Iwant to make sure that the code that I end up shipping to the browseroperates in the way that I'm telling TypeScript it's going to operate andif you're so like if you trust so much the compiler to make sure that yourtypes are all correct and everything then you shouldn't ever run into thesituation.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 errorthrown because unexpected things could happen down the line which couldmake things even worse. So I would really recommend that you don't try totrick the compiler when you tell type script a thing as of a certain typeit better be of that type when you're making an assertion function, youbetter be doing some assertions.I think that's important though. Anyway, I hope that's interesting. Have a
wonderful awesome typescript.
