A TypeScript transformer that generates JSON schemas and validators from TypeScript interfaces
This package provides a TypeScript transformer that generates JSON schemas and validators from TypeScript interfaces. It uses ts-json-schema-generator to introspect types and ajv to generate validator functions. Functions and schema are generated inline at compile time using a custom typescript transformer.
You can also generate mock objects (using json-schema-faker) and safely parse JSON strings into the given types.
- typescript >= 5
You can use any package manager. I prefer pnpm, but yarn and npm should work fine.
pnpm add -D @nrfcloud/ts-json-schema-transformer
# OR
yarn add -D @nrfcloud/ts-json-schema-transformer
# OR
npm install -D @nrfcloud/ts-json-schema-transformer
Both ts-patch and ttypescript
should work, though I recommend ts-patch
since it seems better supported.
pnpm add -D ts-patch
# You'll want to add this line to your package.json prepare script
pnpm ts-pach install -s
# --- OR ---
pnpm add -D ttypescript
{
"compilerOptions": {
"plugins": [
{
"transform": "@nrfcloud/ts-json-schema-transformer/dist/transform"
}
]
}
}
import { getSchema, createValidateFn } from "@nrfcloud/ts-json-schema-transformer";
import { getMockObject } from "./index";
export interface InputEvent {
foo: Duration;
// You can add JSDoc tags to include additional schema info
/**
* @format uri
*/
other: string;
stuff: union;
}
/**
* @format date-time
*/
type Duration = string;
interface Type1 {
name: "Type1";
value: string;
}
interface Type2 {
name: "Type2";
/**
* @minimum 0
* @maximum 100
*/
value: number;
stuff: object;
}
// Most syntax is supported, even unions and conditional types
type union = Type1 | Type2;
// Generate a JSON schema
const schema = getSchema<InputEvent>();
// Generate an AJV validator function
const validator = createValidateFn<InputEvent>();
// Run the validator
validator({});
// Get the validator errors
console.log(validator.errors);
// Generate a mock object
const mock = getMockObject<InputEvent>();
// Assert method to throw errors upon validation failure
try {
assertValid<InputEvent>(mock);
} catch (error) {
// ... handle error
}
// TS can narrow the type after an assertValid call expression
const fn = (obj: SimpleType | string) => {
assertValid<SimpleType>(obj);
// We know obj is a SimpleType from this point forward
console.log(obj.foo);
};
Generates a JSON schema for the given type. The generic type parameter is the type you want to generate a schema for, and the single input to the function. This function call is replaced by the generated schema at compile time.
Validates an object against the schema for the given type Returns either the validated object or undefined if validation fails.
Creates a validator function for the given type. Returns either the validated object or undefined if validation fails.
Validates an object against the schema for the given type. Returns a boolean indicating whether the object is valid, acting as a type guard.
Generates an AJV validator function for the given type. The generic type parameter is the type you want to generate a validator for, and the single input to the function. This function call is replaced by the generated validator at compile time.
Generate a mock object for the given type. Should support all formats as well as other constraints. You can optionally specify a seed for the random number generator as the second parameter.
Generates a reusable mock function for the given type.
Validates that a given object satisfies the constraints defined in the given generic type parameter's schema. The method will throw an error if validation fails. This function call is replaced a wrapped validator method at compile time.
Generates a reusable assertGuard function for the given type. The function returned by this method can be called with an object to validate it against the schema for the given type. The function will throw an error if validation fails.
Very similar to assertGuard
but returns the passed object instead of narrowing the type.
Generates a reusable assert function for the given type. The function returned by this method can be called with an object to validate it against the schema for the given type. The function will throw an error if validation fails.
Parses a JSON string into the given type. Returns the parsed object if successful, otherwise undefined.
Parses a JSON string into the given type. Throws an error if the input is invalid.
Generates a reusable parse function for the given type.
Generates a reusable assertParse function for the given type.
You can add JSDoc tags to your interfaces and types to add additional schema information. The following tags are supported:
Inputs for these tags are parsed as text.
Adds a description to the schema.
Adds a title to the schema.
Set the id property of the schema.
Add a format validation to the schema
Supported Formats:
- date: full-date according to RFC3339
- time: time (time-zone is mandatory).
- date-time: date-time (time-zone is mandatory).
- duration: duration from RFC3339
- uri: full URI.
- uri-reference: URI reference, including full and relative URIs.
- uri-template: URI template according to RFC6570
- url: full URL.
- email: email address.
- hostname: host name according to RFC1034.
- ipv4: IP address v4.
- ipv6: IP address v6.
- regex: tests whether a string is a valid regular expression by passing it to RegExp constructor.
- uuid: Universally Unique IDentifier according to RFC4122.
- json-pointer: JSON-pointer according to RFC6901.
- relative-json-pointer: relative JSON-pointer according to this draft.
- byte: base64 encoded data according to the openApi 3.0.0 specification
- int32: signed 32 bits integer according to the openApi 3.0.0 specification
- int64: signed 64 bits according to the openApi 3.0.0 specification
- float: float according to the openApi 3.0.0 specification
- double: double according to the openApi 3.0.0 specification
- password: password string according to the openApi 3.0.0 specification
- binary: binary string according to the openApi 3.0.0 specification
- iso-date-time: date-time according to ISO 8601
- iso-time: time according to ISO 8601
Adda a regex pattern to the schema.
Adds a JSON schema reference. Not quite working yet.
Add a comment to the schema.
Sets the MIME type of the contents for a string. JSON Schema docs
Sets the content encoding for a string. JSON Schema docs
Sets the discriminating property for a union type.
Maps to the discriminator
property in the JSON schema.
Inputs for these tags are parsed as JSON (strings must be quoted).
Add an example to the schema.
Set the minimum value for a number.
Set the exclusive minimum value for a number.
Set the maximum value for a number.
Set the exclusive maximum value for a number.
Require that a number be a multiple of a given number.
Set the minimum length for a string.
Set the maximum length for a string.
Set the minimum number of properties for an object.
Set the maximum number of properties for an object.
Set the minimum number of items for an array.
Set the maximum number of items for an array.
Require that an array only have unique items
Set a regex pattern for additional property names.
Require that an array contains at least one of a given schema.
Specify a constant value for a property.
NOTE: This is probably better done in typescript by setting a constant type
Provide an array of examples for a property.
Set a default value.
Maps to the if
property in the JSON schema.
JSON Schema docs
Maps to the then
property in the JSON schema.
JSON Schema docs
Maps to the else
property in the JSON schema.
JSON Schema docs
Marks the property as readonly in the schema.
Mask the property as readonly in the schema.
Marks the property as deprecated.
You can configure properties of schema and validator generation in the plugins config within your tsconfig.json
file.
The validation options map to the same options in the AJV library.
The schema options map to the same options in the ts-json-schema-generator library.
Note that not all options are exposed, though more could be added in the future.
{
"compilerOptions": {
"plugins": [
{
"transform": "ts-json-schema-generator",
// Validation options
// Assign default values to the object passed to the validator
"useDefaults": true,
// Coerce properties of the validated object (ex: string to number)
"coerceTypes": false,
// Remove additional properties from the validated object
"removeAdditional": false,
// How many required properties must be present before a loop is generated.
// Loops are slower, but generated more concise validators
"loopRequired": 20,
// How many enum values must be present before a loop is generated.
"loopEnum": 100,
// Whether to return all errors encoutered or just the first one
"allErrors": true,
// Schema options
// Whether to process jsDoc annotations
// none: Do not use JsDoc annotations.
// basic: Read JsDoc annotations to provide schema properties.
// extended (default): Also read @nullable, and @asType annotations.
"jsDoc": "extended",
// Do not allow additional items on tuples
"strictTuples": false,
// Whether to allow additional properties on objects that don't have index signatures
"additionalProperties": false,
// What schemas should be exposed (given readable names)
// all: Create shared $ref definitions for all types.
// none: Do not create shared $ref definitions.
// export (default): Create shared $ref definitions only for exported types (not tagged as `@internal`).
"expose": "export",
// Whether properties should be sorted (stable)
"sortProps": true,
// Explicitly set the seed used for mock data generation.
// You can disable seeding by setting this false
"seed": "this is a seed"
}
]
}
}
You need to add the transformer to you tsconfig.json
file, or ts-patch / ttypescript are not setup correctly.
Instructions
Currently, this can only be done at runtime.
Simply call getSchema
and run the output through JSON.stringify
and save it to a file.
The validator function returns a boolean, and sets the errors
property on the function to an array of errors.
AJV Docs
Large schemas can generate a substantial amount of code, so creating a reusable function can help reduce the size of the generated code. This can be important in cases where the size of the final bundle is a concern.
The big difference between this library and typia
is that it uses AJV and other off the shelf libraries (ts-json-schema-generator in particular) to generate schemas and code.
This means that the individual components can have separate maintainers with a wider base of support (along with a wider support and feature set).
For our specific use case, typia
lacks support for type aliases and, consequently, nominal types.
For example, we use something like the following to define safe nominal types:
export declare class Tagged<N extends string> {
protected _nominal_: N;
}
// The extra parameter "E" is for creating basic inheritance
export type Nominal<T, N extends string, E extends T & Tagged<string> = T & Tagged<N>> = (T & Tagged<N>) | E;
// 0..255 regex is [0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]
// 0..31 regex is [0-9]|[12][0-9]|3[012]
// CIDR v4 is [0..255].[0..255].[0..255].[0..255]/[0..32]
/**
* @pattern ^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}/([0-9]|[12][0-9]|3[012])$
* @minLength 12
* @maxLength 21
* @example "86.255.0.199/24"
*/
export type CidrV4 = Nominal<string, "CidrV4">;
We can then use this type to validate the input to functions:
function checkIpInCidrBlock(ip: IPv4, cidr: CidrV4): boolean {
...
}
const testCidr = "192.168.1.0/24"
// This will fail since the string type is too broad
checkIpInCidrBlock(testCidr)
// This narrows the string type to the nominal one
assertGuard<CidrV4>(testCidr)
checkIpInCidrBlock(testCidr);
Typia is a fantastic library and was a big inspiration for this project.
Contributions are welcome!
Please follow the guidelines:
- Use conventional style commit messages
- Submit a changeset with your PR
pnpm changeset
- Don't introduce any new runtime dependencies either through the index file or generated code
- Run lint and fix before committing