Tightening types on successful insert to not be `object | undefined`
When doing
db.insert(someTable).values(someValues).returning()
what would be the preferred way to narrow the type of the return value from object | undefined
if the insert is successful?
I'm trying to do some seeding where I create some entries in one table and save them as variables, and then attempt to insert the IDs of those entries into another table as a foreign key that's non-nullable and TS tells me that they're potentially undefined, which is true.
Since this is seeding, I know I'm clearing my DB before this, so I know the inserts will succeed and that it's not an issue if they don't) so would the best way to silence these errors just be to add !
to the objects when doing returnedObject!.id
?
more generally, I'm curious if there's a drizzle specific way to chain anything onto the .values({...}).returning()
call that will narrow the type so that undefined
isn't an option. I didn't see anything in the docs that would do this. I tried adding onConflictDoNothing
and onConflictDoUpdate
to see if they'd narrow the type but they don't.
Is there something in the docs I'm missing, or alternatively has anybody written an extension method for PgInsertBuilder
(or any of the other builders) so that you could do something like
const [row] = await db.insert(table).values({}).returning().assertSuccess()
and then the type of row
couldn't be undefined?
I know that this is basically the same as adding
if (!row) throw new Error("failed to insert row")
after each insert, I was just curious if there's a better way.0 Replies