Suppose I need to create an instance of interface A { x: number, a: string}
from a JSON string const str = {"x":0,"a":""}
in Typescript.
If the JSON does not contain the required properties x
and a
of the required types I would like to get an exception, e.g. property "a" is missing
or property "x" is not a number
.
I can parse the JSON string into an object const obj = JSON.parse(str)
and check if obj
contains properties x
and a
manually. I wonder whether there is a better way to create an instance of A
from JSON without validating the properties of input JSON and their types manually.
What is the simplest way to deserialize a JSON to an instance of an interface with validation ?