Issue
Why does the following snippet not compile, and how is the ES6 JSON interface supposed to be used?
let myVar: JSON = {"id": "12"};
Gives the following error message: Type '{ id: string; }' is not assignable to type 'JSON'. Object literal may only specify known properties, and '"id"' does not exist in type 'JSON'.
My IDE gives the following definition for JSON, but I can’t understand it:
interface JSON {
readonly [Symbol.toStringTag]: string;
}
Solution
JSON
is a global object defined by the JS specification designed to hold the parse
and stringify
methods for converting between JS data structures and JSON texts.
It isn't a type. It isn't supposed to be used as one.
When creating a custom object format, you are supposed to define your own type (although it isn't useful to do so here, but might be if you define a function elsewhere that you need to pass the object to as an argument). When dealing with JSON, you are dealing with strings.
type MyFormat = {
id: string;
}
let myVar: MyFormat = {"id": "12"};
let myJSON: string = JSON.stringify(myVar);
Answered By - Quentin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.