Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
typescript-json-schema
Advanced tools
typescript-json-schema generates JSON Schema files from your Typescript sources
The typescript-json-schema npm package is a tool that generates JSON schemas from your TypeScript types. This can be particularly useful for validating JSON data, generating documentation, or ensuring consistency between your TypeScript code and JSON data structures.
Generate JSON Schema from TypeScript Interface
This feature allows you to generate a JSON schema from a TypeScript interface. The code sample demonstrates how to set up the schema generator, specify the TypeScript file, and generate the schema for a specific interface.
const TJS = require('typescript-json-schema');
// Settings for the schema generator
const settings = {
required: true
};
// Path to the TypeScript file
const files = ["./example.ts"];
// Generate the schema
const program = TJS.getProgramFromFiles(files);
const schema = TJS.generateSchema(program, "MyInterface", settings);
console.log(JSON.stringify(schema, null, 2));
Generate JSON Schema with Custom Settings
This feature allows you to customize the settings for the JSON schema generation. The code sample demonstrates how to use custom settings such as `noExtraProps` and `propOrder` to control the schema generation process.
const TJS = require('typescript-json-schema');
// Custom settings for the schema generator
const settings = {
required: true,
noExtraProps: true,
propOrder: true
};
// Path to the TypeScript file
const files = ["./example.ts"];
// Generate the schema
const program = TJS.getProgramFromFiles(files);
const schema = TJS.generateSchema(program, "MyInterface", settings);
console.log(JSON.stringify(schema, null, 2));
Generate JSON Schema for Multiple Interfaces
This feature allows you to generate JSON schemas for multiple TypeScript interfaces at once. The code sample demonstrates how to specify multiple interfaces and generate their schemas in a single operation.
const TJS = require('typescript-json-schema');
// Settings for the schema generator
const settings = {
required: true
};
// Path to the TypeScript file
const files = ["./example.ts"];
// Generate the schema
const program = TJS.getProgramFromFiles(files);
const schema = TJS.generateSchema(program, ["MyInterface1", "MyInterface2"], settings);
console.log(JSON.stringify(schema, null, 2));
The typescript-to-json-schema package is another tool for generating JSON schemas from TypeScript types. It offers similar functionality to typescript-json-schema but with a different API and potentially different performance characteristics.
The ts-json-schema-generator package is designed to generate JSON schemas from TypeScript types with a focus on simplicity and ease of use. It provides a straightforward API and is often used for quick schema generation tasks.
The json-schema-to-typescript package works in the opposite direction, generating TypeScript types from JSON schemas. This can be useful for ensuring that your TypeScript code matches a given JSON schema, providing a complementary tool to typescript-json-schema.
Generate json-schemas from your Typescript sources.
npm install typescript-json-schema -g
typescript-json-schema project/directory/tsconfig.json TYPE
To generate files for only some types in tsconfig.json
specify
filenames or globs with the --include
option. This is especially useful for large projects.
In case no tsconfig.json
is available for your project, you can directly specify the .ts files (this in this case we use some built-in compiler presets):
typescript-json-schema "project/directory/**/*.ts" TYPE
The TYPE
can either be a single, fully qualified type or "*"
to generate the schema for all types.
Usage: typescript-json-schema <path-to-typescript-files-or-tsconfig> <type>
Options:
--refs Create shared ref definitions. [boolean] [default: true]
--aliasRefs Create shared ref definitions for the type aliases. [boolean] [default: false]
--topRef Create a top-level ref definition. [boolean] [default: false]
--titles Creates titles in the output schema. [boolean] [default: false]
--defaultProps Create default properties definitions. [boolean] [default: false]
--noExtraProps Disable additional properties in objects by default. [boolean] [default: false]
--propOrder Create property order definitions. [boolean] [default: false]
--required Create required array for non-optional properties. [boolean] [default: false]
--strictNullChecks Make values non-nullable by default. [boolean] [default: false]
--esModuleInterop Use esModuleInterop when loading typescript modules. [boolean] [default: false]
--skipLibCheck Use skipLibCheck when loading typescript modules. [boolean] [default: false]
--useTypeOfKeyword Use `typeOf` keyword (https://goo.gl/DC6sni) for functions. [boolean] [default: false]
--out, -o The output file, defaults to using stdout
--validationKeywords Provide additional validation keywords to include [array] [default: []]
--include Further limit tsconfig to include only matching files [array] [default: []]
--ignoreErrors Generate even if the program has errors. [boolean] [default: false]
--excludePrivate Exclude private members from the schema [boolean] [default: false]
--uniqueNames Use unique names for type symbols. [boolean] [default: false]
--rejectDateType Rejects Date fields in type definitions. [boolean] [default: false]
--id Set schema id. [string] [default: ""]
--defaultNumberType Default number type. [choices: "number", "integer"] [default: "number"]
--tsNodeRegister Use ts-node/register (needed for require typescript files). [boolean] [default: false]
--constAsEnum Use enums with a single value when declaring constants. [boolean] [default: false]
--experimentalDecorators Use experimentalDecorators when loading typescript modules.
[boolean] [default: true]
import { resolve } from "path";
import * as TJS from "typescript-json-schema";
// optionally pass argument to schema generator
const settings: TJS.PartialArgs = {
required: true,
};
// optionally pass ts compiler options
const compilerOptions: TJS.CompilerOptions = {
strictNullChecks: true,
};
// optionally pass a base path
const basePath = "./my-dir";
const program = TJS.getProgramFromFiles(
[resolve("my-file.ts")],
compilerOptions,
basePath
);
// We can either get the schema for one file and one type...
const schema = TJS.generateSchema(program, "MyType", settings);
// ... or a generator that lets us incrementally get more schemas
const generator = TJS.buildGenerator(program, settings);
// generator can be also reused to speed up generating the schema if usecase allows:
const schemaWithReusedGenerator = TJS.generateSchema(program, "MyType", settings, [], generator);
// all symbols
const symbols = generator.getUserSymbols();
// Get symbols for different types from generator.
generator.getSchemaForSymbol("MyType");
generator.getSchemaForSymbol("AnotherType");
// In larger projects type names may not be unique,
// while unique names may be enabled.
const settings: TJS.PartialArgs = {
uniqueNames: true,
};
const generator = TJS.buildGenerator(program, settings);
// A list of all types of a given name can then be retrieved.
const symbolList = generator.getSymbols("MyType");
// Choose the appropriate type, and continue with the symbol's unique name.
generator.getSchemaForSymbol(symbolList[1].name);
// Also it is possible to get a list of all symbols.
const fullSymbolList = generator.getSymbols();
getSymbols('<SymbolName>')
and getSymbols()
return an array of SymbolRef
, which is of the following format:
type SymbolRef = {
name: string;
typeName: string;
fullyQualifiedName: string;
symbol: ts.Symbol;
};
getUserSymbols
and getMainFileSymbols
return an array of string
.
The schema generator converts annotations to JSON schema properties.
For example
export interface Shape {
/**
* The size of the shape.
*
* @minimum 0
* @TJS-type integer
*/
size: number;
}
will be translated to
{
"$ref": "#/definitions/Shape",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Shape": {
"properties": {
"size": {
"description": "The size of the shape.",
"minimum": 0,
"type": "integer"
}
},
"type": "object"
}
}
}
Note that we needed to use @TJS-type
instead of just @type
because of an issue with the typescript compiler.
You can also override the type of array items, either listing each field in its own annotation or one annotation with the full JSON of the spec (for special cases). This replaces the item types that would have been inferred from the TypeScript type of the array elements.
Example:
export interface ShapesData {
/**
* Specify individual fields in items.
*
* @items.type integer
* @items.minimum 0
*/
sizes: number[];
/**
* Or specify a JSON spec:
*
* @items {"type":"string","format":"email"}
*/
emails: string[];
}
Translation:
{
"$ref": "#/definitions/ShapesData",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Shape": {
"properties": {
"sizes": {
"description": "Specify individual fields in items.",
"items": {
"minimum": 0,
"type": "integer"
},
"type": "array"
},
"emails": {
"description": "Or specify a JSON spec:",
"items": {
"format": "email",
"type": "string"
},
"type": "array"
}
},
"type": "object"
}
}
}
This same syntax can be used for contains
and additionalProperties
.
integer
type aliasIf you create a type alias integer
for number
it will be mapped to the integer
type in the generated JSON schema.
Example:
type integer = number;
interface MyObject {
n: integer;
}
Note: this feature doesn't work for generic types & array types, it mainly works in very simple cases.
require
a variable from a file(for requiring typescript files is needed to set argument tsNodeRegister
to true)
When you want to import for example an object or an array into your property defined in annotation, you can use require
.
Example:
export interface InnerData {
age: number;
name: string;
free: boolean;
}
export interface UserData {
/**
* Specify required object
*
* @examples require("./example.ts").example
*/
data: InnerData;
}
file example.ts
export const example: InnerData[] = [{
age: 30,
name: "Ben",
free: false
}]
Translation:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"data": {
"description": "Specify required object",
"examples": [
{
"age": 30,
"name": "Ben",
"free": false
}
],
"type": "object",
"properties": {
"age": { "type": "number" },
"name": { "type": "string" },
"free": { "type": "boolean" }
},
"required": ["age", "free", "name"]
}
},
"required": ["data"],
"type": "object"
}
Also you can use require(".").example
, which will try to find exported variable with name 'example' in current file. Or you can use require("./someFile.ts")
, which will try to use default exported variable from 'someFile.ts'.
Note: For examples
a required variable must be an array.
Inspired and builds upon Typson, but typescript-json-schema is compatible with more recent Typescript versions. Also, since it uses the Typescript compiler internally, more advanced scenarios are possible. If you are looking for a library that uses the AST instead of the type hierarchy and therefore better support for type aliases, have a look at vega/ts-json-schema-generator.
npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString
And connect via the debugger protocol.
FAQs
typescript-json-schema generates JSON Schema files from your Typescript sources
The npm package typescript-json-schema receives a total of 361,982 weekly downloads. As such, typescript-json-schema popularity was classified as popular.
We found that typescript-json-schema demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.