DusterTheFirst
DusterTheFirst

Reputation: 357

Generate JSON schema from typescript

I am trying to create a typescript doc-generator, but to do so, i need to parse a typescript file into something more easily readable

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
  }

would come from something like this

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;
}

how would I accomplish this, preferably in the browser, but if that is not possible I could also do it using node.js

Upvotes: 19

Views: 25816

Answers (3)

Pranit Bhatt
Pranit Bhatt

Reputation: 1

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

Command Line use:

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

I used like this,

./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;}

Upvotes: 0

Jarno
Jarno

Reputation: 7212

ts-json-schema-generator works quite well for me.

command-line use:

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

programmatic use:

// 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);

There is also typescript-json-schema, but it can produce invalid schemas in some cases.

Upvotes: 11

DusterTheFirst
DusterTheFirst

Reputation: 357

TypeDoc has a similar feature, you can use the --json tag to get data about the module in JSON format

it is not exactly what I was looking for, but can be used to accomplish the same thing

Upvotes: 3

Related Questions