简体   繁体   English

打字稿:mongoose模式的静态方法

[英]Typescript: static methods for mongoose schemas

I'm trying to implement a mongoose model with TypeScript, nothing fancy, just try to make it work. 我正在尝试用TypeScript实现一个mongoose模型,没什么特别的,只是试着让它工作。 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? 有这个指针吗?

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. 您需要扩展Schema的类型以包括您正在扩展的字段,否则打字稿不知道它。 This is a good answer for extending a type. 这是扩展类型的一个很好的答案。 How do you explicitly set a new property on `window` in TypeScript? 如何在TypeScript中的`window`上显式设置新属性?

If you look at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts , you will see the general typings for mongoose. 如果你看看https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts ,你会看到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 架构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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM