Skip to content

Add functionality to generate typescript interface from schema #492

@bruceborrett

Description

@bruceborrett

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}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions