2

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 ?

Michael
  • 41,026
  • 70
  • 193
  • 341
  • 1
    You could try one of the approaches at this question: `https://stackoverflow.com/questions/43909566/get-keys-of-a-typescript-interface-as-array-of-strings` to 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. – ArtHare Jan 08 '21 at 19:39
  • Thanks. This solution looks complicated :(( I would not like to validate the keys manually. Too much boilerplate, I think. – Michael Jan 08 '21 at 19:43
  • 1
    I think the class-that-implements might not be too bad. `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 assert `typeof objectToCheck[keyName] === typeof stubClassInstance[keyName]` – ArtHare Jan 08 '21 at 19:53
  • Are you trying to validate an object with some schema? Like what `yup` does? – c0m1t Jan 08 '21 at 21:04
  • @ArtHare Thanks again. Your solution looks fine. I will try it. – Michael Jan 08 '21 at 21:33
  • @c0m1t No, I don't use any schema. I did not know what `yup` is. Thanks for pointing me out. I will take a look. – Michael Jan 08 '21 at 21:35
  • duplicate of [Runtime data validation for TypeScript](https://stackoverflow.com/questions/65479057/runtime-data-validation-for-typescript) and [Generate JSON schema from typescript](https://stackoverflow.com/questions/45939657/generate-json-schema-from-typescript) – milahu Apr 01 '22 at 10:17

0 Answers0