longshotlabs / simpl-schema

A JavaScript schema validation package that supports direct validation of MongoDB update modifier objects
https://www.npmjs.com/package/simpl-schema
MIT License
560 stars 114 forks source link

Add functionality to generate typescript interface from schema #492

Open bruceborrett opened 5 months ago

bruceborrett commented 5 months ago

It would be very convenient to be able to generate typescript interfaces from a schema, similar to Zod's infer method (https://zod.dev/?id=type-inference) or Yup's InferType method (https://github.com/jquense/yup#typescript-integration).

This allows the schema to be the source of truth for all types and keeps schemas and types in sync.

Example usage:

const userSchema = SimplSchema({
  name: string
});

export interface User = schema.inferType();

export const Users = Meteor.Collection<User>('users');

Some work has also been done here, which may be of interest - https://github.com/OlivierChirouze/schema-to-types

Since there is already new functionality recently added to convert to json schema, perhaps something like this can simply be used to convert the json schema to the typescript interface - https://www.npmjs.com/package/json-schema-to-typescript - however I did try this and that package only supports JsonSchema4 whereas toJsonSchema produces JSONSchema7.

Cherry on the cake would be additional methods for generating mutator types. For example, insert type will have all values with autovalues set to optional, update type will be of mongo modifier shape.

Eg.


const userSchema = SimplSchema({
  name: string,
  createdAt: {
    type: Date,
    autoValue: function() {
      return new Date();
    }
  }
});

export interface User = schema.inferType(); // {name: String, createdAt: Date}
export interface InsertUser = schema.inferInsertType(); // {name: String, createdAt?: Date}
export interface UpdateUser = schema.inferUpdateType(); // {$set: {name?: String, createdAt?: Date}}
github-actions[bot] commented 5 months ago

Thank you for submitting an issue!

If this is a bug report, please be sure to include, at minimum, example code showing a small schema and any necessary calls with all their arguments, which will reproduce the issue. Even better, you can link to a saved online code editor example, where anyone can immediately run the code and see the issue.

If you are requesting a feature, include a code example of how you imagine it working if it were implemented.

If you need to edit your issue description, click the [...] and choose Edit.

Be patient. This is a free and freely licensed package that I maintain in my spare time. You may get a response in a day, but it could also take a month. If you benefit from this package and would like to see more of my time devoted to it, you can help by sponsoring.

ThaumRystra commented 3 months ago

There was also this experiment posted to the Meteor forum , which takes a different approach