Abhisar Tripathi
Abhisar Tripathi

Reputation: 1659

Can anyone explain me what is happening in this line of typescript code?

const res = JSON.parse(resObj as string)

I am new to typescript can anyone please explain what is happening in the above code ?

Upvotes: 0

Views: 154

Answers (3)

Alex Mapley
Alex Mapley

Reputation: 922

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse has some good docs on this.

Let's assume resObj is some json blob like '{"result":true, "count":42}'

First of all

resObj as string

means that we are typecasting whatever resObj is to a string. This is just to make sure we're working with the right types, when we call that JSON.parse function.

const res = JSON.parse(resObj as string)

is then doing the following:

  1. Casting resObj as a string
  2. Feeding this string casted resObj variable into JSON.parse, which will return an Object { result: true, count: 42 }
  3. Assign res to be equal to that Object { result: true, count: 42 }

And that's it. You should now be able to access fields on our res object, like res.result or res.count

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 84982

resObj as string is a type assertion. It tells typescript "treat resObj as though it's a string, even though the information you have says its not".

Type assertions are occasionally necessary when you know something that typescript does not. But you're basically telling typescript to not check your work, so if you use it when resObject actually isn't a string, then typescript cannot point this out to you, and you may get an exception or other unexpected behavior at runtime.

Upvotes: 4

LaytonGB
LaytonGB

Reputation: 1404

resObj is being interpreted as type string, and then parsed as a JSON string.

The reason for declaring as string is most likely that resObj is being returned by an external or async service which does not return a single type of object, but in this instance the user knows the return will be a string (whereas typescript does not).

JSON.parse is then converting the string into a usable Javascript object. Eg:

const resObj = `{"prop1":"foo","prop2":3,"prop3":false}`;
const res = JSON.parse(resObj);
console.log(res);

Upvotes: 3

Related Questions