# Using with TypeScript
# Additional functionality
Ajv takes advantage of TypeScript type system to provide additional functionality that is not possible in JavaScript:
- utility types
JSONSchemaType
andJTDSchemaType
to convert data type into the schema type to simplify writing schemas, both for JSON Schema (but without union support) and for JSON Type Definition (with tagged unions support). - utility type
JTDDataType
to convert JSON Type Definition schema into the type of data that it defines. - compiled validation functions are type guards that narrow the type after successful validation.
- validation errors for JSON Schema are defined as tagged unions, for type-safe error handling.
- when utility type is used, compiled JTD serializers only accept data of correct type (as they do not validate that the data is valid) and compiled parsers return correct data type.
# Utility types for schemas
For the same example as in Getting started:
- ensure strictNullChecks is true
See this test (opens new window) for an advanced example.
# Utility type for JTD data type
You can use JTD schema to construct the type of data using utility type JTDDataType
TypeScript limitation
Note that it's currently not possible for JTDDataType
to know whether the compiler is inferring timestamps as strings or Dates, and so it conservatively types any timestamp as string | Date
. This is accurate, but often requires extra validation on the part of the user to confirm they're getting the appropriate data type.
# Type-safe error handling
With both JSON Schema and JSON Type Definition, the validation error type is an open union, but it can be cast to tagged unions (using validation keyword as tag) for easier error handling.
Continuing the example above:
# Type-safe parsers and serializers
With typescript, your compiled parsers and serializers can be type-safe, either taking their type from schema type or from type parameter passed to compilation functions.
This example uses the same data and schema types as above:
# Type-safe unions
JSON Type Definition only supports tagged unions, so unions in JTD are fully supported for JTDSchemaType
and JTDDataType
.
JSON Schema is more complex and so JSONSchemaType
has limited support for type safe unions.
JSONSchemaType
will type check unions where each union element is fully specified as an element of an anyOf
array or oneOf
array.
Additionally, unions of primitives will type check appropriately if they're combined into an array type
, e.g. {type: ["string", "number"]}
.
TypeScript limitation
Note that due to current limitation of TypeScript, JSONSchemaType cannot verify that every element of the union is present, and the following example is still valid const schema: JSONSchemaType<number | string> = {type: "string"}
.
Here's a more detailed example showing several union types: