validate a json object against a typescript interface in typescript

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.ts
npm install ajv
16 chars
2 lines

Next, define your TypeScript interface as you normally would, but with an additional __brand property:

index.ts
interface Person {
  __brand: 'Person';
  name: string;
  age: number;
}
73 chars
6 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:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "number" }
  },
  "required": ["name", "age"],
  "additionalProperties": false
}
176 chars
10 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.ts
import Ajv from 'ajv';

const ajv = new Ajv();
const validate = ajv.compile(schema);
85 chars
5 lines

You can then use the validate function to check if a JSON object matches your TypeScript interface:

index.ts
const person: unknown = {
  name: "John Doe",
  age: 30
};

if (validate(person) && (<Person>person).__brand === "Person") {
  // `person` is a valid `Person` object
} else {
  // `person` is not a valid `Person` object
}
222 chars
11 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