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
bloberenober
bloberenober13mo ago
well, you don't need to specify the type explicitly, other than that it's fine
Flo
Flo13mo 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
bloberenober
bloberenober13mo ago
set "noUncheckedIndexedAccess": true in tsconfig
Flo
Flo13mo ago
oh didn't know that exists ohh that produces so much chaos in my codebase 😅
Mario564
Mario56413mo ago
you could also add ?. before [0] so the type is User | undefined
grimrippa
grimrippa13mo 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
yamiteru13mo ago
Why not just use .get()?
coycoylaniba
coycoylaniba10mo ago
does .get() returns object or array? nevermind. i tested it, it returns object | undefined, thanks ❤️