DT
Drizzle Team•7mo ago
camiaei

Why select() always expects to have matches?

hi. i encountered this issue:
const [record] = await db
.select()
.from(day)
.where(eq(id, 123456));
const [record] = await db
.select()
.from(day)
.where(eq(id, 123456));
record is inferred to have a non-nullable type, even though the queried record with the ID 123456 may not exist in the database. Can anyone tell me if I am doing something wrong? I was migrating some queries to select() but this behavior makes it pretty unusable 😕 Thanks
4 Replies
Sillvva
Sillvva•7mo ago
Make sure you have noUncheckedIndexedAccess: true in your tsconfig.json file
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
+ "noUncheckedIndexedAccess": true,
"noErrorTruncation": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
+ "noUncheckedIndexedAccess": true,
"noErrorTruncation": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
}
Sillvva
Sillvva•7mo ago
In TypeScript without that option, when you have an array like string[] for example, string[0] is string. However, the array could be empty. That's where the option comes in and makes it string | undefined unless you check that the index exists.
const arr: string[] = [];
const [item] = arr;
// Before option: item is string
// After option: item is string | undefined

if (item) {
item // string
}
const arr: string[] = [];
const [item] = arr;
// Before option: item is string
// After option: item is string | undefined

if (item) {
item // string
}
The same is true for objects with unknown keys like const obj: Record<string, string> = {}
camiaei
camiaei•7mo ago
thanks, however now I'm getting a couple of rather curious errors. I don't like typescript very much 😪
Want results from more Discord servers?
Add your server