Skip to content

feat: generate type maps.#1787

Draft
LeviticusMB wants to merge 2 commits into
vega:nextfrom
Divine-Software:typemaps
Draft

feat: generate type maps.#1787
LeviticusMB wants to merge 2 commits into
vega:nextfrom
Divine-Software:typemaps

Conversation

@LeviticusMB

Copy link
Copy Markdown

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
Copy Markdown
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
Copy Markdown
Member

Thanks for the pull request.

@domoritz

domoritz commented Jan 7, 2024

Copy link
Copy Markdown
Member

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
Copy Markdown
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.

2 participants