select with limit of 1

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];
const user: User | undefined = (await db.select().from(users).where(eq(users.id, userId)).limit(1))[0];
8 Replies
Dan
Dan2y ago
well, you don't need to specify the type explicitly, other than that it's fine
Flo
FloOP2y ago
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. idk it feels a bit weird that the select returns an array with a limit of 1
Dan
Dan2y ago
set "noUncheckedIndexedAccess": true in tsconfig
Flo
FloOP2y ago
oh didn't know that exists ohh that produces so much chaos in my codebase 😅
Mario564
Mario5642y ago
you could also add ?. before [0] so the type is User | undefined
grimrippa
grimrippa2y ago
I've been doing something like
const [user] = await db.select().from(users).where(eq(users.id, userId)).limit(1);
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.
yamiteru
yamiteru2y ago
Why not just use .get()?
taijitu ☯
taijitu ☯16mo ago
does .get() returns object or array? nevermind. i tested it, it returns object | undefined, thanks ❤️
Want results from more Discord servers?
Add your server