New types in v2 have some issues with single/multiple return types, e.g. with returning("*")
See original GitHub issueWe’re having some issues with typings in 2.0. (v2.1.2 - latest)
Breaking out into multiple issues, I can log separately if needed.
- This example from Objection’s Postgres Returning Tricks actually is typed as returning an array - not a single object. So this code in the official Recipe won’t work. (The recipe code may just be wrong since patch().where() seems like it could always return multiple, unless querying for ‘id’ is a specific case in the types that indicates singular return.)
const jennifer = await Person.query()
.patch({ firstName: 'Jenn', lastName: 'Lawrence' })
.where('id', 1234)
.returning('*');
-
findOne() is typed as returning
T
, notT | undefined
. This means we always have to manually addas T | undefined
, as findOne could always fail. In TS there are things that can fail but nevertheless return only T (array indexing for example), but findOne function seems far more analagous to JS array.find() which returnsT | undefined
, as I believe findOne should. Or, perhaps a tryFindOne function would make sense, which could return undefined. -
I’d expect these two queries to both return single User objects:
await User.query().patch({}).findOne({}).returning("*");
await User.query().findOne({}).patch({}).returning("*");
However, the former is typed as returning a single User and the latter returns an array. I’d suggest the latter is the more intuitive usage (find object then patch it) and should return a single User.
I’m sure I’m not aware of all the interactions in the types and whether the changes above are mutually compatible. We’re huge fans of Objection on our team, thanks for all your work contributing this to the JS/TS community!
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:5 (3 by maintainers)
1 can be fixed by moving
findOne
/findById
/first
afterreturning
. There’s no way to make the typings work in every case, believe me, I’ve tried.2 is an unfortunate tradeoff I had to make to implement some other features a lot of people wanted.
An insane amount of my time went to writing the new typings. You’ll just have to live with the little flaws or write better typings yourself.
You can add those methods to a custom query builder yourself. Or even override a bunch of methods to return the type you want.