Raw sql nullable types, sql<Type | undefined>

VVolks5/10/2023
const result = await db.select({
  customField: sql<Type | null>`...`


This gets inferred to SQL<any>

Is there a way to have a nullable type when using raw sql?
Bbloberenober5/10/2023
yes, it should use the exact type passed as the generic
Bbloberenober5/10/2023
could you post your whole query and the definition of Type?
VVolks5/11/2023
Sorry, mistook the issue a bit, it seems that without the .mapWith() its inferred properly, but if its mapped then it is always non-nullable. Probably a niche situation but still a bit unusual, here's my whole thing

destination: sql<Point | null>`CASE WHEN driver_shifts.ride_id IS NOT NULL THEN active_rides.destination END`.mapWith(driverShifts.location),


Type (property) destination: SQL<Point>

But if I remove the mapWith

It correctly is inferred to (property) destination: SQL<Point | null>

export const driverShifts = pgTable('driver_shifts', {
    id: uuid('id').primaryKey().defaultRandom(),
        createdAt: timestamp('created_at').defaultNow().notNull(),
    location: pointDB("location").notNull(),
});


The pointDB is a custom PGColumn. But I don't think I can pass it to mapWith but rather I have to use a column from the table, this is a seperate question, don't think its related to the above problem
Bbloberenober5/11/2023
OK I see - this is an edge case I didn't think about
We automatically assign the result type when you call .mapWith based on the mapper return type
So the fastest fix on your side would be to make a custom mapper function that returns a nullable result, and pass it into mapWith
something like
function mapper(value: any): Point | null {
  return driverShifts.location.mapFromDriverValue(value);
}

.mapWith(mapper)
VVolks5/11/2023
Yeah quite a niche situation, glad I caught it. Thanks @Dan Kochetov
VVolks5/11/2023
Will you create an issue on GH if this warrants one? I would like to follow it
Bbloberenober5/11/2023
You can create it yourself if you'd like 🙂