ts-json-schema-generator
ts-json-schema-generator copied to clipboard
feat: generate type maps.
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().)
BTW that tool I was talking about is now available at https://github.com/Divine-Software/divine-companions/tree/master/judgement-cli.
Thanks for the pull request.
The tests fail so I mark this as draft for now.
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!