drizzle-team / drizzle-team/drizzle-orm

[BUG]: Wrong type returned when using 'leftJoin' on a subquery using a 'mapWith'

Open
#1,421 3 comments 0 reactions 1 assignee Claimed by @Angelelz View on GitHub
bug priority qb/crud
Dominant language
TypeScript
Stars
35.8k
Forks
1.6k
Avg merge
2d 7h
Merged PRs (30d)
4

Description

### What version of `drizzle-orm` are you using?

0.28.6

### What version of `drizzle-kit` are you using?

_No response_

### Describe the Bug

The following code reproduces the unexpected result:
```typescript
import { eq, sql } from "drizzle-orm";
import {
datetime,
int,
mysqlTable,
serial,
varchar,
} from "drizzle-orm/mysql-core";
import { db } from "~/server/db";

const usersTable = mysqlTable("users", {
id: serial("id"),
name: varchar("name", { length: 255 }),
});

const userEventsTable = mysqlTable("user_events", {
id: serial("id"),
userId: int("user_id").notNull(),
event: varchar("event", { length: 255 }).notNull(),
timestamp: datetime("timestamp").notNull(),
});

const lastEventTimestamps = db
.select({
userId: userEventsTable.userId,
lastEventTimestamp: sql`MAX(${userEventsTable.timestamp})`
.mapWith(userEventsTable.timestamp)
.as("last_event_timestamp"),
})
.from(userEventsTable)
.groupBy(userEventsTable.userId)
.as("last_event_timestamps");

const [example] = await db
.select({
id: usersTable.id,
name: usersTable.name,
lastEventUserId: lastEventTimestamps.userId,
lastEventTimestamp: lastEventTimestamps.lastEventTimestamp,
})
.from(usersTable)
.leftJoin(lastEventTimestamps, eq(usersTable.id, lastEventTimestamps.userId));

if (example) {
const unexpected = example;

const expected = example as {
id: number;
name: string | null;
lastEventUserId: number | null;
lastEventTimestamp: Date | null;
};
}
```
The typing of `unexpected` should match that of `expected` because it using a `leftJoin`. The issue seems to arise when using `mapWith`. The prop `lastEventTimestamp` does not have the possible type of `null` from the `leftJoin` like `lastEventUserId` does.

Thank you for any insight into this issue.

### Expected behavior

The expected typing:
Screenshot 2023-10-25 at 8 01 05 PM

The returned typing:
Screenshot 2023-10-25 at 7 56 44 PM

### Environment & setup

_No response_

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.