ts-json-schema-generator icon indicating copy to clipboard operation
ts-json-schema-generator copied to clipboard

feat: generate type maps.

Open LeviticusMB opened this issue 2 years ago • 4 comments

I'm testing the waters here; not sure how you feel about this. I could maintain a fork of course, but I'd prefer not to ...

This PR adds support for generating some schema metadata in addition to the actual JSON schema. The metadata could be used to generate type-safe validation functions directly by a tool that embeds this library.

To demonstrate, I also added a CLI option -m that writes out a TypeScript "type map"—similar to how "event maps" are often used when defining on() or addEventListener():

import type { MyObject, Base } from "./test/valid-data/class-generics/main.ts";

export default interface Definitions {
    [`MyObject`]: MyObject;
    [`Base<string>`]: Base<string>;
    [`Base<boolean>`]: Base<boolean>;
}

This type map makes it possible to define the following function:

import type Definitions from "./schema.d.ts";
import schema from "./schema.json";

export function is<K extends keyof Definitions>(type: K, value: object): value is Definitions[K] {
    console.log("validating using subschema", schema.definitions[type]);
    return true; // FIXME: Use Ajv or something to check
}

which, in turn, may be used like this:

const obj = { a: 1, b: "2", c: { a: "3" }, d: { a: true } };

if (is("MyObject", obj)) {
    console.assert(typeof obj.a === "number");
}

(That is, inside the if branch, TypeScript now knows that obj is MyObject, and the editor can show completions for the type argument to is().)

LeviticusMB avatar Oct 02 '23 20:10 LeviticusMB

BTW that tool I was talking about is now available at https://github.com/Divine-Software/divine-companions/tree/master/judgement-cli.

LeviticusMB avatar Oct 06 '23 20:10 LeviticusMB

Thanks for the pull request.

domoritz avatar Oct 15 '23 13:10 domoritz

The tests fail so I mark this as draft for now.

domoritz avatar Jan 07 '24 12:01 domoritz

Yeah sorry I intended to fix a few issues that I had noticed and add tests for it, but I've not yet taken the time to do so.

Pleased to hear that you will consider the PR though!

LeviticusMB avatar Jan 07 '24 16:01 LeviticusMB