Essential Types And Notations 20 exercises
solution

Decoding the JSON.parse Error

Let's look a bit closer at the error message we got when calling JSON.parse:


Expected 0 type arguments, but got 1.

This message indicates that TypeScript is not expecting anything inside the angle braces when calling JSON.parse. To resolve this error, we simply remove the angl

Loading solution

Transcript

00:00 Let's start by decoding the error that we're getting on the type argument of json.parse. We have expected zero type arguments but got one. That's indicating that it's not expecting to be parsed anything inside these curly or these angle braces. So let's remove this. So now, wow, it's happy. Fantastic.

00:19 But you can see that the parse data is typed as any. This is because if we hover over json.parse, it always returns any. That's a bit of a troubling thing, actually, with TypeScript and json.parse, but we will talk about that later. But how do we get around that? Because we actually want our parse data to be the correct type.

00:38 We know that any is assignable to anything and anything is assignable to any. So that means that we can actually just pull in this and just say parse data is this type. So parse data now, we've given it a variable type annotation with name, string, and age number, and everything is working great.

00:55 And because it's actually being parsed any, it's pretty happy with this. So this is a way that you can get around json.parse not accepting any type arguments. And because we can see here that it doesn't have any angle brackets on this little section there just before the parentheses.

01:11 So some functions will take in type arguments and some functions just won't. And your job is to try to get around that sometimes.