从TypeScript生成JSON模式

16
我正在尝试创建一个TypeScript文档生成器,但为了实现这一目标,我需要将TypeScript文件解析为更易于阅读的格式。
EX:
"Command": {
    "description": "A command object for the command handler",
    "constructor": [
      {
        "name": "name",
        "type": "string",
        "optional": false,
        "default": null,
        "description": "Name of the command"
      },
      {
        "name": "callback",
        "type": "(event: CommandContext) => void",
        "optional": false,
        "default": null,
        "description": "Callback for the command"
      }
    ],
    "properties": [
      {
        "name": "name",
        "description": "Name of the command",
        "type": "string"
      },
      {
        "name": "fullname",
        "description": "Fullname of the command",
        "type": "string"
      }
    ],
    "methods": [
      {
        "name": "canRun",
        "description": "Checks all permission checks and verifies if a command can be run",
        "parameters": [
          {
            "name": "context",
            "type": "CommandContext",
            "optional": false,
            "default": null,
            "description": "The context for the command",
            "returns": "PermissionCheckResult"
          }
        ]
      }
    ],
    "events": null
  }

可能来自于这样的东西

export declare class Command {
    /**
     * Name of the command
     */
    name: string;
    /**
     * Fullname of the command
     */
    fullname: string;
    /**
     * Create a command
     * @param name - Name of the command
     * @param callback - Callback for the command
     */
    constructor(name: string, callback: (event: CommandContext) => void);
    /**
     * Checks all permission checks and verifies if a command can be run
     * @param context - The context for the command
     */
    canRun(context: CommandContext): boolean;
}

我该如何实现这一点,最好在浏览器中,但如果不可能的话,我也可以使用node.js完成


3
目前尚无成熟的解决方案。以下是一些相关链接:https://github.com/YousefED/typescript-json-schema,https://github.com/Microsoft/TypeScript/issues/14419,https://github.com/Microsoft/TypeScript/issues/3628#issuecomment-298236279。 - Paleo
3个回答

8

ts-json-schema-generator 对我来说效果非常好。

命令行使用:

npx ts-json-schema-generator -p types.ts > types.json

编程使用:

// generate schema from typescript types
const tsj = require("ts-json-schema-generator");
const fs = require("fs");
const output_path = "some-type.schema.json";
/** @type {import('ts-json-schema-generator/dist/src/Config').Config} */
const config = {
  path: "path/to/index.d.ts",
  tsconfig: "path/to/tsconfig.json",
  type: "SomeType", // "*" for all types
};
const schemaGenerator = tsj.createGenerator(config);
const schema = schemaGenerator.createSchema(config.type);
const schemaString = JSON.stringify(schema, null, 2);
fs.writeFileSync(output_path, schemaString);

// use the schema to validate some data
import Ajv from "ajv"
const ajv = new Ajv({
  strict: true,
  allErrors: true,
});
ajv.validateSchema(schema);
if (ajv.errors) {
  console.dir(ajv.errors, { depth: null });
  throw new Error("The schema is not valid");
}
const validate = ajv.compile(schema);
const data = {
  foo: 1,
  bar: "abc"
};
const valid = validate(data);
if (!valid) console.log(validate.errors);

还有 typescript-json-schema,但在某些情况下可能会生成无效的模式。


现在还可以作为VSCode扩展使用。https://marketplace.visualstudio.com/items?itemName=marcoq.vscode-typescript-to-json-schema - bocko
有没有办法在客户端使用它?而不是使用Node运行它或CLI?我想创建一个返回模式的函数。我使用Cypress。 - sham

2

TypeDoc具有类似的功能,您可以使用--json标签以JSON格式获取有关模块的数据。

虽然不是我所要寻找的完全相同的内容,但它可以用来达到同样的目的。


我尝试使用typedoc和--json标志将webpack类型定义文件转换为JSON模式,但最终并没有成功,如此处所示。你是如何完成的? - Mateja Petrovic

0

https://www.npmjs.com/package/typescript-json-schema

命令行使用:

./node_modules/.bin/typescript-json-schema <path-to-typescript-files-or-tsconfig> <type> --out schema.json

我像这样使用:

./node_modules/.bin/ts-json-schema-generator index.ts Book --out schema.json

index.ts

export interface Book {
author: string;
/**
 * The size of the shape.
 *
 * @minimum 0
 * @TJS-type integer
 * @items.optional true
 */
pages: number;
genre: BookGenre;}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接