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 ?

7
  • 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. Commented Jan 8, 2021 at 19:39
  • Thanks. This solution looks complicated :(( I would not like to validate the keys manually. Too much boilerplate, I think. Commented Jan 8, 2021 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] Commented Jan 8, 2021 at 19:53
  • Are you trying to validate an object with some schema? Like what yup does? Commented Jan 8, 2021 at 21:04
  • @ArtHare Thanks again. Your solution looks fine. I will try it. Commented Jan 8, 2021 at 21:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.