|
| 1 | +import { expectType, expectNotType } from 'tsd'; |
| 2 | + |
| 3 | +import { MongoClient } from '../../src/mongo_client'; |
| 4 | +import type { CollectionInfo, ListCollectionsCursor } from '../../src/operations/list_collections'; |
| 5 | + |
| 6 | +const db = new MongoClient('').db(); |
| 7 | + |
| 8 | +type EitherCollectionInfoResult = CollectionInfo | Pick<CollectionInfo, 'name' | 'type'>; |
| 9 | + |
| 10 | +// We default to the CollectionInfo result type |
| 11 | +expectType<ListCollectionsCursor<Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo>>( |
| 12 | + db.listCollections() |
| 13 | +); |
| 14 | +// By default it isn't narrowed to either type |
| 15 | +expectNotType<ListCollectionsCursor<Pick<CollectionInfo, 'name' | 'type'>>>(db.listCollections()); |
| 16 | +expectNotType<ListCollectionsCursor<CollectionInfo>>(db.listCollections()); |
| 17 | + |
| 18 | +// Testing each argument variation |
| 19 | +db.listCollections(); |
| 20 | +db.listCollections({ a: 2 }); |
| 21 | +db.listCollections({ a: 2 }, { batchSize: 2 }); |
| 22 | + |
| 23 | +const collections = await db.listCollections().toArray(); |
| 24 | +expectType<EitherCollectionInfoResult[]>(collections); |
| 25 | + |
| 26 | +const nameOnly = await db.listCollections({}, { nameOnly: true }).toArray(); |
| 27 | +expectType<Pick<CollectionInfo, 'name' | 'type'>[]>(nameOnly); |
| 28 | + |
| 29 | +const fullInfo = await db.listCollections({}, { nameOnly: false }).toArray(); |
| 30 | +expectType<CollectionInfo[]>(fullInfo); |
| 31 | + |
| 32 | +const couldBeEither = await db.listCollections({}, { nameOnly: Math.random() > 0.5 }).toArray(); |
| 33 | +expectType<EitherCollectionInfoResult[]>(couldBeEither); |
| 34 | + |
| 35 | +// Showing here that: |
| 36 | +// regardless of the option the generic parameter can be used to coerce the result if need be |
| 37 | +// note the nameOnly: false, yet strings are returned |
| 38 | +const overridden = await db |
| 39 | + .listCollections<Pick<CollectionInfo, 'name' | 'type'>>({}, { nameOnly: false }) |
| 40 | + .toArray(); |
| 41 | +expectType<Pick<CollectionInfo, 'name' | 'type'>[]>(overridden); |
| 42 | +const overriddenWithToArray = await db |
| 43 | + .listCollections({}, { nameOnly: false }) |
| 44 | + .toArray<Pick<CollectionInfo, 'name' | 'type'>>(); |
| 45 | +expectType<Pick<CollectionInfo, 'name' | 'type'>[]>(overriddenWithToArray); |
0 commit comments