Skip to content

Better type inference for egg-mongoose #67

@Celend

Description

@Celend

Hi!, We're trying to use egg.js in production with mongoose, but we notice a problem about the typing for Mongoose with egg-ts-mongoose plugin.

Mongoose itself has the typing solution(separate interface declaration or use ts-mongoose), and the egg-ts-helper also generated a correct type file of model files(interface IModel), Awesome!
But when using the model in service by this.ctx.model, the model type is referred to the egg.Context.model in egg-ts-mongoose/index.d.ts(https://github.com/eggjs/egg-mongoose/blob/master/index.d.ts#L28), which type is [key: string]: mongoose.Model<any>.

So in the service, the model type is Model<any>, it's very stupid! and the solution also very easy, just override the type of context.model to IModel, by edit typing/index.d.ts as below:

import 'egg';

declare module 'egg' {
    // add below lines
    interface Context {
        model: IModel
    }
}

(Edit the typing/model/index.d.ts should has same result)

I think this job can not be done by egg-mongoose, because the interface IModel is a generated file.

I'm using WebStorm 2020.2, but I think the VSCode should has the same problem, because the context.model type refer to egg-mongoose seems a correct behavior or maybe I wrong :D

Thanks!

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