drizzle-team / drizzle-team/drizzle-orm
[BUG]: Wrong type returned when using 'leftJoin' on a subquery using a 'mapWith'
- 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:
The returned typing:
### Environment & setup
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.