Skip to content

Cursor and Collection types are not generic #41

@danielegarciav

Description

@danielegarciav

Under the current type definitions, collections and cursors return documents that are always typed as Object. This means that when using TypeScript, documents must always be type-asserted to a concrete type before being used:

const db = new zango.Db('mydb');
const people = db.collection('people');

const person = people.find({ name: 'John' });
person.name = 'Mike'; // ERROR: Property 'ok' does not exist on type 'Object'.

interface Person {
  name: string;
}

const person2 = people.find({ name: 'John' }) as Person;
person.name = 'Mike'; // OK

This happens because current type definitions are hard-typed to Object and do not allow generics:

zangodb/src/zangodb.d.ts

Lines 21 to 31 in 868babf

export class Collection {
name: string;
aggregate(pipeline: Object[]): Cursor;
find(expr: Object, projection_spec?: Object): Cursor;
findOne(expr: Object, projection_spec?: Object,
cb?: ResultCallback<Object>): Promise<Object>;
insert(docs: Object|Object[], cb?: Callback): Promise<void>;
remove(expr: Object, cb?: Callback): Promise<void>;
update(expr: Object, spec: Object, cb?: Callback): Promise<void>;
}

We could get inspired by mongodb's type definitions at DefinitelyTyped, and generalize Cursor and Collection, allowing the library consumer to set the document's interface for a given collection, falling back to Record<string, any> if the type parameter is not supplied:

mongodb's Collection type signature - allows a type parameter

mongodb's Collection#findOne type signature - leverages collection type parameter

Using a similar sytem, we could accomplish the following with TypeScript:

interface Person {
  name: string;
}

const db = new zango.Db('mydb');
const people = db.collection<Person>('people');

const person = people.find({ name: 'John' }); // typeof person == Person
person.name = 'Mike'; // OK

I can go ahead and write a quick PR to fix this if you'd like.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions