Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cursor and Collection types are not generic #41

Open
danielegarciav opened this issue Jun 18, 2021 · 0 comments
Open

Cursor and Collection types are not generic #41

danielegarciav opened this issue Jun 18, 2021 · 0 comments

Comments

@danielegarciav
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant