首页 > 解决方案 > 如何在 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

标签: typescript

解决方案


我们可以使用模块扩充来将属性添加到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

推荐阅读