TypeScript: Don't type array method callbacks - a podcast by Kent C. Dodds

from 2021-01-30T05:40:20

:: ::

Hello friends, this is a little bit later than usual but I just wanted to
get this in because I want to do this every weekday. So today I want totalk about TypeScript and in particular map. So I wrote a blog post
recently that talked about converting typescript or fetch a fetchimplemented or calling fetch in a function over to TypeScript because when
you call fetch the return value from the dot JSON on that response is goingto be any and so you have to explicitly.
Give that a type annotation. And anyway, one of the as I was migrating thiscode one of the things that I pointed out was that like we were iterating
over some of the values that came back from that response.json call. And inthe process of migrating the code if you just go about it in a certain way
before you add the type annotation, you'll find that iterating over it
requires that you type that map.Callback function. And so in our example, we had an array of errors that
could come back from this API call and we're going to iterate over those
array of errors to kind of join them up into a single error. And so theidea in in this example was you would get a implicit error or implicit any
problem on that map callback function and as a result you had to type thatexplicitly and so I just say okay, well the argument to this is.
An object that has a message property. So anytime you are you have a dotmap call on an array and type script is telling you that you have to give
an explicit type to the arguments of that callback function. This wouldalso apply to like a filter or any array of any kind.
So anytime that callback function requires that you add type annotations.That is a sign that the array itself is not typed. So you want to skip the
whole typing of that?Callback function and go back to where that arrayitself is defined and make sure that it has a proper type annotation of
some kind so that you don't have to worry about typing the callback for an
array method.So if you're ever doing a radon map or a radar every or a radar sum or a
radar filter or reduce or any of that and type script is saying, hey, Idon't know what type this is. This isn't implicit any you need to add a
type for this function.Don't do that go fix the array first. Hope that's helpful. Take care.

Further episodes of 3 Minutes with Kent

Further podcasts by Kent C. Dodds

Website of Kent C. Dodds