【发布时间】:2020-12-25 22:13:36
【问题描述】:
我正在尝试扩展第三方库类 mongooseJs,以便我可以在其中拥有一些自定义功能。我过去用 Javascript 做过这个,像这样
const mongoose = require("mongoose");
class CustomMongoose extends mongoose.Mongoose {
myCustomMethod() {
console.log('this is my custom method');
}
}
const a = new CustomMongoose();
a.model("test"); //This method does get called on parent correctly (code wouldn't work until connection is setup but you get the point)
但是,当我尝试在 typescript 中做类似的事情时,如下所示,它给了我一个错误
Type 'CustomMongoose' is missing the following properties from type 'CustomMongooseBase': pluralize, connect, createConnection, disconnect, and 39 more.
此代码
const mongoose = require("mongoose");
import { Schema, Model, Document, Mongoose } from "mongoose";
interface CustomMongooseBase extends Mongoose {
myCustomMethod(): void;
}
class CustomMongoose extends mongoose.Mongoose implements CustomMongooseBase {
myCustomMethod(): void {
console.log('this is my custom method');
}
}
//this is what I would expect to work, if this compiles fine
// const a = new CustomMongoose();
// a.myCustomMethods(); // should work
// a.model("modelName") //should also work, though this is from the base
我想要做的是提供我自己的接口CustomMongooseBase,这反过来又扩展了Mongoose 接口。我希望我的新班级 CustomMongoose 的调用者拥有我的新功能和其他所有内容。所以在具体实现中,我扩展了mongoose.Mongoose,它实现了Mongoose接口所需的所有方法,我的自定义类实现了我自己的接口所需的新方法myCustomMethod,所以这应该可以工作,但是不是。
我在这里做错了什么? (打字稿新手,所以想了解一下)
====略有不同的变化与不同的错误====
import { Mongoose } from "mongoose";
export interface CustomMongooseBase extends Mongoose //extending at the interface level so that consumers have the full signature of mine as well as parent interface
{
myCustomMethod(): void;
}
class CustomMongoose extends Mongoose implements CustomMongooseBase {
myCustomMethod(): void {
console.log("this is my custom method");
}
}
//this is what I would expect to work, if this compiles fine
// const a = new CustomMongoose();
// a.myCustomMethods(); // should work
// a.model("modelName") //should also work, though this is from the base
现在又出现了一个不同的错误
Non-abstract class 'CustomMongoose' does not implement inherited abstract member 'ConnectionBase' from class 'typeof import("mongoose")'.ts(2515)
这些是我的 package.json 依赖项
"dependencies": {
"@types/mongoose": "^5.7.36",
"@types/node": "^14.6.4",
"mongoose": "^5.10.3"
}
【问题讨论】:
-
感谢@T.J.Crowder,感谢您的建议。是的,在我的实际代码中,我就是这样的。让我也纠正一下这个问题。
-
您的问题有
const mongoose = require("mongoose");紧随其后的是import { Schema, Model, Document, Mongoose } from "mongoose";这真的很奇怪。通常你使用 either CommonJS (require) 或 ESM (import)。你不要混合它们。
标签: javascript typescript mongoose interface extends