从打字稿生成 JSON 模式

Generate JSON schema from typescript

我正在尝试创建一个 typescript 文档生成器,但为此,我需要将 typescript 文件解析为更易于阅读的内容

前:

"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

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

这不是我要找的东西,但可以用来完成同样的事情

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,但在某些情况下它会产生无效的模式。