[英]Typescript: static methods for mongoose schemas
我正在嘗試用TypeScript實現一個mongoose模型,沒什么特別的,只是試着讓它工作。 此代碼編譯但有警告:
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);
但打字稿正在抱怨:
error TS2339: Property 'methods' does not exist on type 'Schema'.
我認為我需要擴展一些接口。 有這個指針嗎?
默認情況下,架構類型不允許擴展。 在打字稿中,接口是開放的並且是可擴展的。 您需要擴展Schema的類型以包括您正在擴展的字段,否則打字稿不知道它。 這是擴展類型的一個很好的答案。 如何在TypeScript中的`window`上顯式設置新屬性?
如果你看看https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts ,你會看到mongoose的一般類型。
您最有可能做的是以下內容,但我不知道您是否可以擴展課程:
架構extended.d.ts
module "mongoose" {
export class Schema {
methods:any
}
}
然后在你的代碼中:
///<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.