Typescript: mongoose模式的静态方法

4

我正在尝试使用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);

但是 TypeScript 报错了:
错误 TS2339:类型“Schema”上不存在属性“methods”。
我猜需要扩展一些接口,有什么指针吗?
1个回答

0

默认情况下,模式类型不允许扩展。在TypeScript中,接口是开放的并且可扩展的。您需要扩展Schema的类型以包括您正在扩展的字段,否则TypeScript将不知道它。这是扩展类型的好答案。如何在TypeScript中显式设置`window`上的新属性?

如果您查看https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/mongoose/mongoose.d.ts,您将看到mongoose的一般类型。

您最有可能要做的是以下操作,尽管我不知道是否可以扩展类:

schema-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

非常好,除了如果我导入变量就无法工作。 从'mongoose'导入{Schema} 抛出导入声明与'Schema'的本地声明冲突。 - Nico
你还需要扩展包含该模式的模块,而不是直接创建模式。查看Schema的类型定义,你会看到它属于哪个模块。 - ArcSine
我不确定我是否理解正确。你能详细说明一下吗? - Nico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接