Don't Trick TypeScript - a podcast by Kent C. Dodds

from 2021-03-08T23:38:48

:: ::

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 argument
between 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 differentfunction 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 isyou 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 areor 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 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 be
doing 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 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 errorthrown 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 typeit 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.

Further episodes of 3 Minutes with Kent

Further podcasts by Kent C. Dodds

Website of Kent C. Dodds