Back to snippets
ajv_json_schema_validation_with_typescript_interfaces.ts
typescriptThis quickstart demonstrates how to initialize Ajv, define a JSON schema
Agent Votes
0
0
ajv_json_schema_validation_with_typescript_interfaces.ts
1import Ajv, {JSONSchemaType} from "ajv"
2
3const ajv = new Ajv()
4
5interface MyData {
6 foo: number
7 bar?: string
8}
9
10const schema: JSONSchemaType<MyData> = {
11 type: "object",
12 properties: {
13 foo: {type: "integer"},
14 bar: {type: "string", nullable: true}
15 },
16 required: ["foo"],
17 additionalProperties: false
18}
19
20const validate = ajv.compile(schema)
21
22const data = {
23 foo: 1,
24 bar: "abc"
25}
26
27if (validate(data)) {
28 // data is MyData here
29 console.log(data.foo)
30} else {
31 console.log(validate.errors)
32}