typescript - 如何在 Typescript 中向导入的库模块添加新的原型方法/属性?
问题描述
我有以下代码:
import mongoose from 'mongoose';
const { ObjectId } = mongoose.Types;
// adds new getter property to ObjectId's prototype
Object.defineProperty(ObjectId.prototype, 'hex', {
get() {
return this.__id || (this.__id = this.toHexString());
},
configurable: true,
enumerable: false,
});
如何hex
在打字稿中添加到 mongoose.Types.ObjectId 类?
'mongoose' 的类型通过以下方式导入@types/mongoose
解决方案
我们可以使用模块扩充来将属性添加到ObjectId
. 在这种情况下,问题是找到ObjectId
实际所在的位置。
如果我们查看 in 的定义,ObjectId
我们mongoose.Types
会发现:
var ObjectId: ObjectIdConstructor;
type ObjectIdConstructor = typeof mongodb.ObjectID & {
(s?: string | number): mongodb.ObjectID;
};
所以返回类型new ObjectId()
实际上是mongodb.ObjectID
,让我们看看它的样子:
export { ObjectID /* … */} from 'bson';
所以,这里我们发现ObjectID
只是一个从 的重新导出'bson'
,如果我们看一下定义,bson
我们最终会找到类定义:
export class ObjectID { … }
把它们放在一起,我们得到:
import * as mongoose from 'mongoose';
const { ObjectId } = mongoose.Types;
declare module "bson" {
export interface ObjectID {
hex: string
}
}
// adds new getter property to ObjectId's prototype
Object.defineProperty(ObjectId.prototype, 'hex', {
get() {
return this.__id || (this.__id = this.toHexString());
},
configurable: true,
enumerable: false,
});
new ObjectId().hex
推荐阅读
- php - 如何使用 PHP 一次更新多个方括号字符串
- sql - 如何在一组日期和时间之间切换
- javascript - 有没有办法在反应最终形式中禁用嵌套字段名称功能?
- amazon-web-services - 如何更改附加到弹性 beantalk 的负载均衡器
- angular - 错误 TS2554:预期 2 个参数,但使用 @ViewChild 得到 1 个
- visual-studio-code - 创建主题和语法颜色时是否可以在 Visual Studio 代码中使用颜色变量
- java - 错误: throw new UnsupportedOperationException("方法未反编译
- search - 如何修复 Flutter 中的“搜索栏下方显示的内容”?
- javascript - 如何将 highcharts 插件添加到 highcharts-vue(highcharts vue 包装器)
- python - Pandas 合并 2 数据框