diff --git a/src/db.ts b/src/db.ts index 2629cffe301..aed434a24e1 100644 --- a/src/db.ts +++ b/src/db.ts @@ -226,18 +226,17 @@ export class Db { * @param options - Optional settings for the command * @param callback - An optional callback, a Promise will be returned if none is provided */ - createCollection(name: string): Promise>; createCollection( name: string, - callback: Callback> - ): void; + options?: CreateCollectionOptions + ): Promise>; createCollection( name: string, - options: CreateCollectionOptions - ): Promise>; + callback: Callback> + ): void; createCollection( name: string, - options: CreateCollectionOptions, + options: CreateCollectionOptions | undefined, callback: Callback> ): void; createCollection( diff --git a/test/types/community/db/createCollection.test-d.ts b/test/types/community/db/createCollection.test-d.ts new file mode 100644 index 00000000000..0f49808422e --- /dev/null +++ b/test/types/community/db/createCollection.test-d.ts @@ -0,0 +1,82 @@ +import { expectType } from 'tsd'; + +import { + MongoClient, + ObjectId, + Collection, + CreateCollectionOptions, + AnyError, + Callback +} from '../../../../src/index'; + +const client = new MongoClient(''); +const db = client.db('test'); + +interface SubTestSchema { + field1: string; + field2: string; +} + +type FruitTypes = 'apple' | 'pear'; + +// test with collection type +interface TestSchema { + _id: ObjectId; + stringField: string; + numberField: number; + optionalNumberField?: number; + dateField: Date; + fruitTags: string[]; + maybeFruitTags?: FruitTypes[]; + readonlyFruitTags: ReadonlyArray; + subInterfaceField: SubTestSchema; + subInterfaceArray: SubTestSchema[]; +} + +const options: CreateCollectionOptions = {}; + +// createCollection + +expectType>>(db.createCollection('test')); + +expectType>>(db.createCollection('test', options)); + +// ensure we can use the create collection in a promise based wrapper function +function extendedPromiseBasedCreateCollection( + name: string, + optionalOptions?: CreateCollectionOptions +): Promise> { + return db.createCollection(name, optionalOptions); +} + +expectType>>(extendedPromiseBasedCreateCollection('test')); + +expectType( + db.createCollection('test', (err, collection) => { + expectType(err); + expectType | undefined>(collection); + }) +); + +expectType( + db.createCollection('test', options, (err, collection) => { + expectType(err); + expectType | undefined>(collection); + }) +); + +// ensure we can use the create collection in a callback based wrapper function +function extendedCallbackBasedCreateCollection( + name: string, + callback: Callback>, + optionalOptions?: CreateCollectionOptions +): void { + db.createCollection(name, optionalOptions, callback); +} + +expectType( + extendedCallbackBasedCreateCollection('test', (err, collection) => { + expectType(err); + expectType | undefined>(collection); + }) +);