{"id":13392540,"url":"https://github.com/YousefED/typescript-json-schema","last_synced_at":"2025-03-13T18:31:51.452Z","repository":{"id":1631550,"uuid":"43307254","full_name":"YousefED/typescript-json-schema","owner":"YousefED","description":"Generate json-schema from your Typescript sources","archived":false,"fork":false,"pushed_at":"2024-09-19T17:24:47.000Z","size":1368,"stargazers_count":3156,"open_issues_count":178,"forks_count":322,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-10-29T11:28:12.288Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/YousefED.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-09-28T14:51:08.000Z","updated_at":"2024-10-27T07:03:24.000Z","dependencies_parsed_at":"2023-02-12T18:30:23.918Z","dependency_job_id":"e6e8c7a2-80df-4a6d-90ab-47e4d5716661","html_url":"https://github.com/YousefED/typescript-json-schema","commit_stats":{"total_commits":482,"total_committers":128,"mean_commits":3.765625,"dds":0.5124481327800829,"last_synced_commit":"75e599aaef6a57e849dbb3e1ff0b6f3749937b10"},"previous_names":[],"tags_count":84,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousefED%2Ftypescript-json-schema","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousefED%2Ftypescript-json-schema/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousefED%2Ftypescript-json-schema/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/YousefED%2Ftypescript-json-schema/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/YousefED","download_url":"https://codeload.github.com/YousefED/typescript-json-schema/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243459110,"owners_count":20294340,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:00:27.139Z","updated_at":"2025-03-13T18:31:51.440Z","avatar_url":"https://github.com/YousefED.png","language":"TypeScript","readme":"# typescript-json-schema\n\n[![npm version](https://img.shields.io/npm/v/typescript-json-schema.svg)](https://www.npmjs.com/package/typescript-json-schema) ![Test](https://github.com/YousefED/typescript-json-schema/workflows/Test/badge.svg)\n\nGenerate json-schemas from your Typescript sources. This library is lightweight and more or less in maintenance mode. For a more complete JSON schema generator, take a look at [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator).\n\n## Features\n\n- Compiles your Typescript program to get complete type information.\n- Translates required properties, extends, annotation keywords, property initializers as defaults. You can find examples for these features in the [api doc](https://github.com/YousefED/typescript-json-schema/tree/master/api.md) or the [test examples](https://github.com/YousefED/typescript-json-schema/tree/master/test/programs).\n\n## Usage\n\n### Command line\n\n- Install with `npm install typescript-json-schema -g`\n- Generate schema from a typescript type: `typescript-json-schema project/directory/tsconfig.json TYPE`\n\nTo generate files for only _some_ types in `tsconfig.json` specify\nfilenames or globs with the `--include` option. This is especially useful for large projects.\n\nIn 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):\n\n- Generate schema from a typescript type: `typescript-json-schema \"project/directory/**/*.ts\" TYPE`\n\nThe `TYPE` can either be a single, fully qualified type or `\"*\"` to generate the schema for all types.\n\n```\nUsage: typescript-json-schema \u003cpath-to-typescript-files-or-tsconfig\u003e \u003ctype\u003e\n\nOptions:\n  --refs                Create shared ref definitions.                               [boolean] [default: true]\n  --aliasRefs           Create shared ref definitions for the type aliases.          [boolean] [default: false]\n  --topRef              Create a top-level ref definition.                           [boolean] [default: false]\n  --titles              Creates titles in the output schema.                         [boolean] [default: false]\n  --defaultProps        Create default properties definitions.                       [boolean] [default: false]\n  --noExtraProps        Disable additional properties in objects by default.         [boolean] [default: false]\n  --propOrder           Create property order definitions.                           [boolean] [default: false]\n  --required            Create required array for non-optional properties.           [boolean] [default: false]\n  --strictNullChecks    Make values non-nullable by default.                         [boolean] [default: false]\n  --esModuleInterop     Use esModuleInterop when loading typescript modules.         [boolean] [default: false]\n  --skipLibCheck        Use skipLibCheck when loading typescript modules.            [boolean] [default: false]\n  --useTypeOfKeyword    Use `typeOf` keyword (https://goo.gl/DC6sni) for functions.  [boolean] [default: false]\n  --out, -o             The output file, defaults to using stdout\n  --validationKeywords  Provide additional validation keywords to include            [array]   [default: []]\n  --include             Further limit tsconfig to include only matching files        [array]   [default: []]\n  --ignoreErrors        Generate even if the program has errors.                     [boolean] [default: false]\n  --excludePrivate      Exclude private members from the schema                      [boolean] [default: false]\n  --uniqueNames         Use unique names for type symbols.                           [boolean] [default: false]\n  --rejectDateType      Rejects Date fields in type definitions.                     [boolean] [default: false]\n  --id                  Set schema id.                                               [string]  [default: \"\"]\n  --defaultNumberType   Default number type.                                         [choices: \"number\", \"integer\"] [default: \"number\"]\n  --tsNodeRegister      Use ts-node/register (needed for require typescript files).  [boolean] [default: false]\n  --constAsEnum         Use enums with a single value when declaring constants.      [boolean] [default: false]\n  --experimentalDecorators  Use experimentalDecorators when loading typescript modules.\n   [boolean] [default: true]\n```\n\n### Programmatic use\n\n```ts\nimport { resolve } from \"path\";\n\nimport * as TJS from \"typescript-json-schema\";\n\n// optionally pass argument to schema generator\nconst settings: TJS.PartialArgs = {\n    required: true,\n};\n\n// optionally pass ts compiler options\nconst compilerOptions: TJS.CompilerOptions = {\n    strictNullChecks: true,\n};\n\n// optionally pass a base path\nconst basePath = \"./my-dir\";\n\nconst program = TJS.getProgramFromFiles(\n  [resolve(\"my-file.ts\")],\n  compilerOptions,\n  basePath\n);\n\n// We can either get the schema for one file and one type...\nconst schema = TJS.generateSchema(program, \"MyType\", settings);\n\n// ... or a generator that lets us incrementally get more schemas\n\nconst generator = TJS.buildGenerator(program, settings);\n\n// generator can be also reused to speed up generating the schema if usecase allows:\nconst schemaWithReusedGenerator = TJS.generateSchema(program, \"MyType\", settings, [], generator);\n\n// all symbols\nconst symbols = generator.getUserSymbols();\n\n// Get symbols for different types from generator.\ngenerator.getSchemaForSymbol(\"MyType\");\ngenerator.getSchemaForSymbol(\"AnotherType\");\n```\n\n```ts\n// In larger projects type names may not be unique,\n// while unique names may be enabled.\nconst settings: TJS.PartialArgs = {\n    uniqueNames: true,\n};\n\nconst generator = TJS.buildGenerator(program, settings);\n\n// A list of all types of a given name can then be retrieved.\nconst symbolList = generator.getSymbols(\"MyType\");\n\n// Choose the appropriate type, and continue with the symbol's unique name.\ngenerator.getSchemaForSymbol(symbolList[1].name);\n\n// Also it is possible to get a list of all symbols.\nconst fullSymbolList = generator.getSymbols();\n```\n\n`getSymbols('\u003cSymbolName\u003e')` and `getSymbols()` return an array of `SymbolRef`, which is of the following format:\n\n```ts\ntype SymbolRef = {\n    name: string;\n    typeName: string;\n    fullyQualifiedName: string;\n    symbol: ts.Symbol;\n};\n```\n\n`getUserSymbols` and `getMainFileSymbols` return an array of `string`.\n\n### Annotations\n\nThe schema generator converts annotations to JSON schema properties.\n\nFor example\n\n```ts\nexport interface Shape {\n    /**\n     * The size of the shape.\n     *\n     * @minimum 0\n     * @TJS-type integer\n     */\n    size: number;\n}\n```\n\nwill be translated to\n\n```json\n{\n    \"$ref\": \"#/definitions/Shape\",\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"definitions\": {\n        \"Shape\": {\n            \"properties\": {\n                \"size\": {\n                    \"description\": \"The size of the shape.\",\n                    \"minimum\": 0,\n                    \"type\": \"integer\"\n                }\n            },\n            \"type\": \"object\"\n        }\n    }\n}\n```\n\nNote that we needed to use `@TJS-type` instead of just `@type` because of an [issue with the typescript compiler](https://github.com/Microsoft/TypeScript/issues/13498).\n\nYou can also override the type of array items, either listing each field in its own annotation or one\nannotation with the full JSON of the spec (for special cases). This replaces the item types that would\nhave been inferred from the TypeScript type of the array elements.\n\nExample:\n\n```ts\nexport interface ShapesData {\n    /**\n     * Specify individual fields in items.\n     *\n     * @items.type integer\n     * @items.minimum 0\n     */\n    sizes: number[];\n\n    /**\n     * Or specify a JSON spec:\n     *\n     * @items {\"type\":\"string\",\"format\":\"email\"}\n     */\n    emails: string[];\n}\n```\n\nTranslation:\n\n```json\n{\n    \"$ref\": \"#/definitions/ShapesData\",\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"definitions\": {\n        \"Shape\": {\n            \"properties\": {\n                \"sizes\": {\n                    \"description\": \"Specify individual fields in items.\",\n                    \"items\": {\n                        \"minimum\": 0,\n                        \"type\": \"integer\"\n                    },\n                    \"type\": \"array\"\n                },\n                \"emails\": {\n                    \"description\": \"Or specify a JSON spec:\",\n                    \"items\": {\n                        \"format\": \"email\",\n                        \"type\": \"string\"\n                    },\n                    \"type\": \"array\"\n                }\n            },\n            \"type\": \"object\"\n        }\n    }\n}\n```\n\nThis same syntax can be used for `contains` and `additionalProperties`.\n\n### `integer` type alias\n\nIf you create a type alias `integer` for `number` it will be mapped to the `integer` type in the generated JSON schema.\n\nExample:\n\n```typescript\ntype integer = number;\ninterface MyObject {\n    n: integer;\n}\n```\n\nNote: this feature doesn't work for generic types \u0026 array types, it mainly works in very simple cases.\n\n### `require` a variable from a file\n\n(for requiring typescript files is needed to set argument `tsNodeRegister` to true)\n\nWhen you want to import for example an object or an array into your property defined in annotation, you can use `require`.\n\nExample:\n\n```ts\nexport interface InnerData {\n    age: number;\n    name: string;\n    free: boolean;\n}\n\nexport interface UserData {\n    /**\n     * Specify required object\n     *\n     * @examples require(\"./example.ts\").example\n     */\n    data: InnerData;\n}\n```\n\nfile `example.ts`\n\n```ts\nexport const example: InnerData[] = [{\n  age: 30,\n  name: \"Ben\",\n  free: false\n}]\n```\n\nTranslation:\n\n```json\n{\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"properties\": {\n        \"data\": {\n            \"description\": \"Specify required object\",\n            \"examples\": [\n                {\n                    \"age\": 30,\n                    \"name\": \"Ben\",\n                    \"free\": false\n                }\n            ],\n            \"type\": \"object\",\n            \"properties\": {\n                \"age\": { \"type\": \"number\" },\n                \"name\": { \"type\": \"string\" },\n                \"free\": { \"type\": \"boolean\" }\n            },\n            \"required\": [\"age\", \"free\", \"name\"]\n        }\n    },\n    \"required\": [\"data\"],\n    \"type\": \"object\"\n}\n```\n\nAlso 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'.\n\nNote: For `examples` a required variable must be an array.\n\n## Background\n\nInspired and builds upon [Typson](https://github.com/lbovet/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](https://github.com/vega/ts-json-schema-generator).\n\n## Debugging\n\n`npm run debug -- test/programs/type-alias-single/main.ts --aliasRefs true MyString`\n\nAnd connect via the debugger protocol.\n","funding_links":[],"categories":["TypeScript","others","Tools","Table of Contents","TypeScript 工具/库/框架"],"sub_categories":["Optimization","JSON","构建工具"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYousefED%2Ftypescript-json-schema","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FYousefED%2Ftypescript-json-schema","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FYousefED%2Ftypescript-json-schema/lists"}