drizzle-team / drizzle-team/drizzle-orm
[BUG]: `Query api` infers nested relation as required even when the relation itself is optional
- Dominant language
- TypeScript
- Stars
- 35.8k
- Forks
- 1.6k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 4
Description
### Report hasn't been filed before.
- [x] I have verified that the bug I'm about to report hasn't been filed before.
### What version of `drizzle-orm` are you using?
0.44.3
### What version of `drizzle-kit` are you using?
0.31.4
### Other packages
_No response_
### Describe the Bug
Using the query api, when a nested relation is added to `with` only if a flag is true, the TypeScript type that in this example findFirst infers still marks that relation as required.
In the example, `author` should be optional in the inferred `post` type.
playground: https://drizzle.run/qggmc67xqaqsog283xapxk2b
```ts
const post = await db.query.posts.findFirst({
where: eq(posts.id, id),
with: { ...(options.withUser && { author: true })}
});
```
**Inferred type**
```ts
type Inferred = {
id: number;
createdAt: Date;
content: string;
authorId: number;
author: { // <-- always required
id: number;
name: string;
createdAt: Date;
};
} | undefined
```
**What I expect**
```ts
type Expected = {
id: number;
createdAt: Date;
content: string;
authorId: number;
author?: { // <-- should be optional
id: number;
name: string;
createdAt: Date;
};
} | undefined
```
Because `author` is only requested when `options.withUser` is true, the property can be `undefined` at runtime and should therefore be `optional` in the type.
Thanks for taking a look!
Contributor guide
Assessment
This issue has not been assessed yet.