Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: generate type maps. #1787

Draft
wants to merge 2 commits into
base: next
Choose a base branch
from
Draft

Conversation

LeviticusMB
Copy link

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
Copy link
Author

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

@domoritz
Copy link
Member

Thanks for the pull request.

@domoritz
Copy link
Member

domoritz commented Jan 7, 2024

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

@domoritz domoritz marked this pull request as draft January 7, 2024 12:22
@LeviticusMB
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants