select with limit of 1

FFlorian5/24/2023
Is there a cleaner way of selecting only one item with proper type safety than this?

const user: User | undefined = (await db.select().from(users).where(eq(users.id, userId)).limit(1))[0];
Bbloberenober5/24/2023
well, you don't need to specify the type explicitly, other than that it's fine
FFlorian5/24/2023
When i don't specify the type it's only User but it can be undefined when the user with that id does not exist in the database. That's why i do that.
FFlorian5/24/2023
idk it feels a bit weird that the select returns an array with a limit of 1
Bbloberenober5/24/2023
set "noUncheckedIndexedAccess": true in tsconfig
FFlorian5/25/2023
oh didn't know that exists
FFlorian5/25/2023
ohh that produces so much chaos in my codebase 😅
MMario5645/25/2023
you could also add ?. before [0] so the type is User | undefined
Ggrimrippa5/25/2023
I've been doing something like
const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);

Which seems to get the inference right but I don't know how typesafe this is.