4

I'm trying to implement a mongoose model with TypeScript, nothing fancy, just try to make it work. This code compiles but with warnings:

import crypto = require('crypto')
import mongoose = require('mongoose')
mongoose.Promise = require('bluebird')
import {Schema} from 'mongoose'

const UserSchema = new Schema({
  name: String,
  email: {
    type: String,
    lowercase: true,
    required: true
  },
  role: {
    type: String,
    default: 'user'
  },
  password: {
    type: String,
    required: true
  },
provider: String,
  salt: String
});

/**
 * Methods
 */
UserSchema.methods = {
  // my static methods... like makeSalt, etc
};

export default mongoose.model('User', UserSchema);

But typescript is complaining:

error TS2339: Property 'methods' does not exist on type 'Schema'.

I presume that i need to extend some interface. Any pointer with this?

Nico
  • 1,241
  • 1
  • 13
  • 29

1 Answers1

0

The Schema typing doesn't allow for extension by default. In typescript interfaces are open and are extensible. You would need to extend the typings for Schema to include the fields you are expanding, otherwise typescript doesn't know about it. This is a good answer for extending a type. How do you explicitly set a new property on `window` in TypeScript?

If you look at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts, you will see the general typings for mongoose.

What you are most likely looking to do is the following, though I don't know if you can extend classes:

schema-extended.d.ts

module "mongoose" {
   export class Schema {
       methods:any
   }
}

Then in your code:

///<reference path="./schema-extended.d.ts" />
//Schema should now have methods as a property.
new Schema().methods
Community
  • 1
  • 1
ArcSine
  • 648
  • 6
  • 14
  • Really good, except that it doesn't work if i imported the variable. import {Schema} from 'mongoose' throws import declaration conflicts with local declaration of 'Schema' – Nico May 03 '16 at 14:58
  • you also have to extend the module that the schema is a part of, not creating the schema directly. Take a look at the typings for Schema, and you will see what module it is in. – ArcSine May 03 '16 at 15:02
  • I'm not sure that i understood correctly. Could you elaborate? – Nico May 03 '16 at 15:05