Definitelytyped: [@types/mongoose] Support for loadClass()

Created on 15 Feb 2019  路  3Comments  路  Source: DefinitelyTyped/DefinitelyTyped

If you know how to fix the issue, make a pull request instead.

  • [x] I tried using the @types/xxxx package and had problems.
  • [x] I tried using the latest stable version of tsc. https://www.npmjs.com/package/typescript
  • [x] I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).
  • [x] [Mention](https://github.com/blog/821-mention-somebody-they-re-notified) the authors (see Definitions by: in index.d.ts) so they can respond.

    • Authors: @simonxca @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @Ethan @vologa @jussikinnula @ondratra @alfirin @idandrd @dominikh @Fazendaaa @NormanPerrin @danmana @stablio

Mongoose now allows loading behavior from an ES6 class into the schema using MySchema.loadClass(MyClass);

This seems to work, but within the class the schema's properties obviously cannot be found.

class MyClass { public foo() { console.log(this.bar); } // this.bar cannot be found, intellisense complains, warnings, etc. }

I'm not sure how to deal with this other than allowing the warnings. If this cannot be addressed, at least maybe we can get a new section for it in the README.md explaining how to use it?

All 3 comments

The solution is to annotate each function in the class with a this parameter, which tells typescript what this refers to when the function is called.

class UserClass {
    getFullName(this: IUser) {
        return `${this.firstName} ${this.lastName}`;
   }
}

@jendrikw Thanks that works!

I actually discovered that if I change from class MyClass { } to class MyClass extends mongoose.Model { } then the problem goes away. But your solution is more accurate and I get full intellisense as well!

I guess this is not a bug. But it should be in the docs, it's so useful.

For the record, your code typechecks because Model has a construct signature of new(doc?: any): T; with T defaulting to any. The result is that you can access any property of this.

Was this page helpful?
0 / 5 - 0 ratings