Generate JSON schema from your TypeScript sources with extensive customization options
npx @tessl/cli install tessl/npm-ts-json-schema-generator@2.4.00
# ts-json-schema-generator
1
2
ts-json-schema-generator is a powerful TypeScript library that generates JSON schemas from TypeScript type definitions. It serves as both a command-line tool and a programmatic library, offering extensive customization options for advanced TypeScript features including generics, conditional types, mapped types, and more.
3
4
## Package Information
5
6
- **Package Name**: ts-json-schema-generator
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install ts-json-schema-generator`
10
11
## Core Imports
12
13
```typescript
14
import { createGenerator, Config, SchemaGenerator } from "ts-json-schema-generator";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { createGenerator } = require("ts-json-schema-generator");
21
```
22
23
For advanced usage (custom parsers/formatters):
24
25
```typescript
26
import {
27
createGenerator,
28
createParser,
29
createFormatter,
30
createProgram,
31
SchemaGenerator,
32
SubTypeFormatter,
33
SubNodeParser,
34
MutableParser,
35
MutableTypeFormatter,
36
BaseType,
37
Context
38
} from "ts-json-schema-generator";
39
```
40
41
## Basic Usage
42
43
```typescript
44
import { createGenerator } from "ts-json-schema-generator";
45
46
// Simple usage
47
const config = {
48
path: "path/to/source/file.ts",
49
tsconfig: "path/to/tsconfig.json",
50
type: "MyInterface", // or "*" for all types
51
};
52
53
const schema = createGenerator(config).createSchema(config.type);
54
console.log(JSON.stringify(schema, null, 2));
55
```
56
57
## Architecture
58
59
ts-json-schema-generator uses a multi-stage architecture:
60
61
- **Program Creation**: TypeScript compiler API creates program from source files
62
- **AST Parsing**: Node parsers convert TypeScript AST nodes to internal type representations
63
- **Type Formatting**: Type formatters convert internal types to JSON schema definitions
64
- **Schema Generation**: SchemaGenerator orchestrates the process and produces final JSON schema
65
66
The library supports extensive customization through:
67
- **Custom Parsers**: Handle new TypeScript syntax or special constructs
68
- **Custom Formatters**: Control JSON schema output format
69
- **Configuration Options**: Fine-tune parsing and generation behavior
70
71
## Capabilities
72
73
### Schema Generation
74
75
Core functionality for generating JSON schemas from TypeScript types with extensive configuration options.
76
77
```typescript { .api }
78
function createGenerator(config: Config): SchemaGenerator;
79
80
interface Config {
81
path?: string;
82
type?: string;
83
tsconfig?: string;
84
expose?: "all" | "none" | "export";
85
jsDoc?: "none" | "extended" | "basic";
86
minify?: boolean;
87
sortProps?: boolean;
88
strictTuples?: boolean;
89
skipTypeCheck?: boolean;
90
encodeRefs?: boolean;
91
topRef?: boolean;
92
markdownDescription?: boolean;
93
extraTags?: string[];
94
additionalProperties?: boolean;
95
functions?: FunctionOptions;
96
schemaId?: string;
97
discriminatorType?: "json-schema" | "open-api";
98
}
99
100
type FunctionOptions = "fail" | "comment" | "hide";
101
102
type CompletedConfig = Config & typeof DEFAULT_CONFIG;
103
```
104
105
[Schema Generation](./schema-generation.md)
106
107
### TypeScript Program Management
108
109
Create and manage TypeScript programs with custom compiler options and file resolution.
110
111
```typescript { .api }
112
function createProgram(config: CompletedConfig): ts.Program;
113
```
114
115
[Program Management](./program-management.md)
116
117
### AST Node Parsing
118
119
Extensible parsing system that converts TypeScript AST nodes to internal type representations.
120
121
```typescript { .api }
122
function createParser(
123
program: ts.Program,
124
config: CompletedConfig,
125
augmentor?: ParserAugmentor
126
): NodeParser;
127
128
type ParserAugmentor = (parser: MutableParser) => void;
129
130
interface NodeParser {
131
createType(node: ts.Node, context: Context, reference?: ReferenceType): BaseType;
132
}
133
134
interface MutableParser {
135
addNodeParser(parser: SubNodeParser): MutableParser;
136
}
137
```
138
139
[AST Parsing](./ast-parsing.md)
140
141
### Type Formatting
142
143
Convert internal type representations to JSON schema definitions with customizable formatters.
144
145
```typescript { .api }
146
function createFormatter(
147
config: CompletedConfig,
148
augmentor?: FormatterAugmentor
149
): TypeFormatter;
150
151
type FormatterAugmentor = (
152
formatter: MutableTypeFormatter,
153
circularReferenceTypeFormatter: CircularReferenceTypeFormatter
154
) => void;
155
156
interface TypeFormatter {
157
getDefinition(type: BaseType): Definition;
158
getChildren(type: BaseType): BaseType[];
159
}
160
161
interface MutableTypeFormatter {
162
addTypeFormatter(formatter: SubTypeFormatter): MutableTypeFormatter;
163
}
164
```
165
166
[Type Formatting](./type-formatting.md)
167
168
### CLI Interface
169
170
Command-line interface with comprehensive options for batch processing and automation.
171
172
```bash
173
npx ts-json-schema-generator --path 'src/**/*.ts' --type 'MyType'
174
```
175
176
[CLI Usage](./cli-usage.md)
177
178
### Custom Extensions
179
180
Create custom parsers and formatters to handle special TypeScript constructs or generate custom JSON schema formats.
181
182
```typescript { .api }
183
interface SubNodeParser extends NodeParser {
184
supportsNode(node: ts.Node): boolean;
185
}
186
187
interface SubTypeFormatter extends TypeFormatter {
188
supportsType(type: BaseType): boolean;
189
}
190
```
191
192
[Custom Extensions](./custom-extensions.md)
193
194
## Types
195
196
### Schema and Definition Types
197
198
```typescript { .api }
199
import type { JSONSchema7 } from "json-schema";
200
201
type Schema = JSONSchema7;
202
type Definition = JSONSchema7;
203
```
204
205
### Base Type System
206
207
```typescript { .api }
208
abstract class BaseType {
209
abstract getId(): string;
210
getName(): string;
211
}
212
```
213
214
### Context
215
216
```typescript { .api }
217
class Context {
218
constructor(reference?: ts.Node);
219
pushArgument(argumentType: BaseType): void;
220
pushParameter(parameterName: string): void;
221
setDefault(parameterName: string, argumentType: BaseType): void;
222
getCacheKey(): string;
223
getArgument(parameterName: string): BaseType;
224
getParameters(): readonly string[];
225
getArguments(): readonly BaseType[];
226
getReference(): ts.Node | undefined;
227
}
228
```
229
230
### Error Types
231
232
```typescript { .api }
233
class BaseError extends Error {
234
format(): string;
235
}
236
237
class UnknownNodeError extends BaseError {}
238
class UnknownTypeError extends BaseError {}
239
class RootlessError extends BaseError {}
240
class MultipleDefinitionsError extends BaseError {}
241
class LogicError extends BaseError {}
242
class ExpectationFailedError extends BaseError {}
243
class JsonTypeError extends BaseError {}
244
class DefinitionError extends BaseError {}
245
class BuildError extends BaseError {}
246
class UnhandledError extends BaseError {}
247
```