19

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

1

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Now also available as a VSCode extension. marketplace.visualstudio.com/…
is there any way i can use that in the client? and not use node to run it or the cli? i want to create a function that returns to me the schema. i use cypress.
3

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

1 Comment

I've tried to convert webpack type definitions file to a json schema using typedoc and the --json flag, but it untimately did not work out as seen here. How did you accomplish it?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.