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 ?
https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-stringsto get an array of keys and validate that they exist. Not perfect since it doesn't validate types as well though. Making an empty class that implements the interface, instantiating an instance, then iterating through its keys seems like the quickest fit.interface MyInterface {a:string;b:string}; class MyInterfaceStub implements MyInterface {a:string="stub";b:string="stub"}; const keysToValidate = Object.keys(new MyInterfaceStub());. It's definitely not excellent (you basically have to declare stuff twice), but it should give you compile-time errors if you forget to update the implementing stub class, and lets you get at an automatically generated run-time array of the key names to check. Also lets you asserttypeof objectToCheck[keyName] === typeof stubClassInstance[keyName]yupdoes?