francescov1 / mongoose-tsgen

A plug-n-play Typescript generator for Mongoose.
102 stars 24 forks source link

Allow nested generics in model initializer #144

Closed richard-jfc closed 3 months ago

richard-jfc commented 4 months ago

I was having trouble using nested generics in the model initializer:

Here's a slightly contrived example:

import { Schema, model } from 'mongoose';
import type { TestDocument, TestModel } from '../interfaces/models.gen';

const TestSchema = new Schema({
  test: {
    type: String,
    default: 'hello',
    required: true,
  },
});

TestSchema.methods = {
  isActive() {
    return true;
  },
};

type SomeGenericType<T = {}> = TestDocument & T;

// The problem occurs here because the generic params for model don't match the regex defined in tsReader.ts
export const Test = model<SomeGenericType<{}>, TestModel>('Test', TestSchema);

This causes the generation of TestMethods to default to (this: TestDocument, ...args: any[]) => any, rather than its true type.

Before fix:

export type TestMethods = {
  isActive: (this: TestDocument, ...args: any[]) => any;
};

After fix:

export type TestMethods = {
  isActive: (this: TestDocument) => boolean;
};

Fix

This PR fixes it by adjusting the regex to allow (& ignore) anything in the generic params for the model initializer.

francescov1 commented 3 months ago

Thanks @richard-jfc, nice job

francescov1 commented 3 months ago

Live in v9.2.14🚀