As a Node developer, chances are that you've already encountered with both Mongoose, and ODM (Object Document Mapper)library helping you connect your app to a MongoDB and TypeScript which is a typed superset of JavaScript that enables the developer to write code with less potential bugs, increased maintainability and smarter code completion through types.

Because both technologies are so popular, it is not a surprise people want to use them together.

A common problem however when using Mongoose with TypeScript is that you have to define both the Mongoose model and TypeScript interface which leads to redundancy.

The real benefit however comes during development time, when Typegoose tells typing information to TypeScript about the decorated Mongoose model. This repels several potential bugs as well as helps the developer through the auto complete feature.

Here Typegoose helps the developer by showing the property on the Mongoose model.

In this scenario if we define a static class method, which equals a static in terms of a Mongoose model, we can see that TypeScript knows about this model function and helps correcting the typo we made.

Conclusion

In this post we've tackled the redundancy issue which is present when you use Mongoose with TypeScript. Instead of defining the Mongoose model and the TypeScript definition file separately, we can use Typegoose to create a TypeScript class which encapsulates the Mongoose model while giving typing information about the underlying model.