TypeScript: Don't type array method callbacks

01/30/2021 , 2m, 55s

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 to talk about TypeScript and in particular map. So I wrote a blog post recently that talked about converting typescript or fetch a fetch implemented 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 going to be any and so you have to explicitly.

Give that a type annotation. And anyway, one of the as I was migrating this code 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 in the 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 the idea 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 that explicitly 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 dot map 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 would also 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 array itself 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, I don'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.