Skip to content

Commit

Permalink
fix(index.d.ts): allow using Types.ObjectId() without new in Type…
Browse files Browse the repository at this point in the history
…Script

Fix #9608
  • Loading branch information
vkarpov15 committed Dec 1, 2020
1 parent 7bf56aa commit 43d6bfc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
13 changes: 12 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1302,10 +1302,21 @@ declare module "mongoose" {
toObject(options: ToObjectOptions & { flattenMaps?: boolean }): any;
}

class ObjectId extends mongodb.ObjectID {
var ObjectId: ObjectIdConstructor;

class _ObjectId extends mongodb.ObjectID {
_id?: ObjectId;
}

// Expose static methods of `mongodb.ObjectID` and allow calling without `new`
type ObjectIdConstructor = typeof _ObjectId & {
(val?: string | number): ObjectId;
};

// var objectId: mongoose.Types.ObjectId should reference mongodb.ObjectID not
// the ObjectIdConstructor, so we add the interface below
interface ObjectId extends mongodb.ObjectID {}

class Subdocument extends Document {
$isSingleNested: true;

Expand Down
8 changes: 8 additions & 0 deletions test/typescript/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ describe('typescript syntax', function() {
assert.equal(errors.length, 1);
assert.ok(errors[0].messageText.includes('Property \'create\' does not exist'), errors[0].messageText);
});

it('objectid', function() {
const errors = runTest('objectid.ts');
if (process.env.D && errors.length) {
console.log(errors);
}
assert.equal(errors.length, 0);
});
});

function runTest(file) {
Expand Down
7 changes: 7 additions & 0 deletions test/typescript/objectid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Types } from 'mongoose';

const oid = new Types.ObjectId();
oid.toHexString();
oid._id;

Types.ObjectId().toHexString();

0 comments on commit 43d6bfc

Please sign in to comment.