【发布时间】:2018-12-28 05:55:10
【问题描述】:
我正在设置一个示意图类型,以了解它如何与 typescript 和 mongoose 一起使用。该示例使用简单的正则表达式验证电子邮件,但我不知道如何注入 mongoose.d.ts 的声明
这是怎么工作的?
email.ts
import * as mongoose from 'mongoose'
function Email (path: any, options: any[]) {
mongoose.SchemaType.call(this, path, options, 'Email')
}
Email.prototype = Object.create(mongoose.SchemaType.prototype)
Email.prototype.cast = function (email: string) {
if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)) {
throw new Error('Invalid email address')
}
return email
}
// Typescript: Property 'Email' does not exist on type 'typeof Types'.
mongoose.Schema.Types.Email = Email
email.d.ts
declare module 'mongoose' {
namespace Schema {
namespace Types {
// ???
}
}
}
我想在方案中得到这个结果
const schema: mongoose.Schema = new mongoose.Schema({
email: {
type: Email
}
})
【问题讨论】:
-
如果您“按原样”使用它,您真的需要将新类型添加到
mongoose.Schema.Types中吗?如果我只是将您对Email的定义和您的方案(除了“隐式this”之外),TS 没有抛出任何错误。 -
ts没有播放错误,我需要挂载不同类型的pos,将在几个不同的模型中使用:(
标签: typescript mongoose