drizzle-team / drizzle-team/drizzle-orm

[BUG]: incorrect `drizzle-zod` schema types if Drizzle schema uses branded types

Open
#4,883 3 comments 1 reaction 0 assignees View on GitHub
bug drizzle/zod
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.5

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

0.31.4

### Other packages

drizzle-zod@0.8.3

### Describe the Bug

If one uses [branded types in a Drizzle schema](https://orm.drizzle.team/docs/column-types/mysql#customizing-data-type), `drizzle-zod` creates an incorrect schema (be it select, insert or update) for that type, which also leads to that schema outputting data of an incorrect type.

For example my attempt at creating a `UserId` branded type resulted in `createSelectSchema(userTable)` outputting a schema that had the following type for the (user) `id`:

```ts
id: z.ZodObject<{
toString: z.ZodType>;
toFixed: z.ZodType>;
toExponential: z.ZodType>;
toPrecision: z.ZodType>;
valueOf: z.ZodType>;
toLocaleString: z.ZodType>;
__brand: z.ZodString;
}, {
out: {};
in: {};
}>;
```

The data type of the user `id` then ends up being;

```ts
{
toString: unknown;
toFixed: unknown;
toExponential: unknown;
toPrecision: unknown;
valueOf: unknown;
toLocaleString: unknown;
__brand: string;
}
```

Others have reported similar issues with `drizzle-zod` and branded types (see [here](https://github.com/drizzle-team/drizzle-orm/issues/4598) and [here](https://github.com/drizzle-team/drizzle-orm/issues/4530#issuecomment-3198330202)).

Zod itself also [supports branded types](https://zod.dev/api#branded-types) however they do branding their own way, so not with `__brand` like most people do it, so for now it doesn't seem like the Drizzle schema branded type specification can be made compatible with that of Zod and the only way to achieve both would be through `drizzle-zod` schema refinements.

[This closed issue from last year](https://github.com/drizzle-team/drizzle-orm/issues/3834) suggests that this is indeed how branded types should be handled but the problem with that is that it will not properly type the results the database returns, which will first need to be parsed by Zod to obtain the correct types, which increases the amount of code required to achieve the same types. Not to mention that regular and Drizzle branded types are not really compatible with those Zod creates.

So to fix this, `drizzle-zod` needs to ignore branded type data when creating schemas, I think.

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.