One way to validate a JSON object against a TypeScript interface is to use a library called Ajv, which is a JSON schema validator.
First, you'll need to install the Ajv package:
index.ts16 chars2 lines
Next, define your TypeScript interface as you normally would, but with an additional __brand
property:
index.ts73 chars6 lines
The __brand
property is used to create a unique, nominal type that can be used to distinguish the interface from other objects.
Then, define a JSON schema that corresponds to your TypeScript interface, using the type
and properties
keywords:
176 chars10 lines
This schema specifies that the JSON object should be an object with name
and age
properties that are strings and numbers respectively.
Finally, load the Ajv library and create a new instance, passing in the JSON schema:
index.ts85 chars5 lines
You can then use the validate
function to check if a JSON object matches your TypeScript interface:
index.ts222 chars11 lines
The validate
function returns a boolean that indicates whether the input JSON object matches the schema. The second condition checks that the __brand
property matches the expected value, ensuring that the JSON object is also a valid instance of your TypeScript interface.
gistlibby LogSnag