drizzle-team / drizzle-team/drizzle-orm

[BUG]: `Query api` infers nested relation as required even when the relation itself is optional

Open
#4,788 1 comment 2 reactions 0 assignees View on GitHub
bug
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

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.