romeerez/orchid-orm

[ask] promise type of db.xxx

bingtsingw opened this issue · 2 comments

I want to write a function that can accept typeof db.xxx as a input, and Promise<typeof db.xx> as output, but the typescript check show an error.

// This do not throw ts error
const func = (q: typeof db.post): typeof db.post => {
  return q.where({})
}
// This throws ts error
const func = async (q: typeof db.post): Promise<typeof db.post> => {
 const id = await xxxxx;
  return q.where({ id : id })
}

How can I write the correct type signature for the async version

typeof db.post is a Promise itself, it extends the Promise type. So typeof db.post is like Promise<Post[]>.

And when we do Promise<typeof db.post>, it's like Promise<Promise<Post[]>>. When awaiting a nested promise, it is awaited down to the bottom, so await func(db.post) will result in just Post[], losing the post query builder completely.

I don't think it's possible to change anything on the lib side to better handle this case.

To prevent awaiting the resulting query, the only way is to wrap it into an object:

// This throws ts error
const func = async (q: typeof db.post): Promise<{ postQuery: typeof db.post }> => {
  const id = await xxxxx;
  return { postQuery: q.where({ id : id }) };
}

I can only suggest making it sync and passing id via argument.

Thank you for your patient explanation.