showing error [symbol.iterator()] in ts generics in knex query

51 views Asked by At
const [user]: T = await db("users").insert(data).returning("*");
// error:Type 'T' must have a '[Symbol.iterator]()' method that returns an iterator.

My knex query typescript giving me error when i tried brackets in knex query to return single object from array.Can someone help me understand to why it is showing me this error even when i passed specific generic type and "user" variable is storing a single object as specified by type.Is there any go through from it, I also tried with .first() instead of square brackets but it shows a different error then.

const user: T = await db("users").insert(data).first().returning("*");

//error: Type 'any[]' is not assignable to type 'T'.
//  'T' could be instantiated with an arbitrary type which could be unrelated to 'any[]'.

2

There are 2 answers

0
Lior Kupers On BEST ANSWER

Remove the .first(). Not sure it works well together with the returning(). Since it will be returning an array in ALL cases, you may as well do T[]. It should accept it.

const user: T[] = await db("users").insert(data).returning("*");

Good luck

2
Michel Floyd On

Simply do:

const user: T = await db("users").select("*").first();

.returning() is for inserts, updates, and deletes, not selects.