-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Creating a custom type for number, strings, etc #1331
Comments
This is similar to the idea behind "branded" types, which is discussed here: #3 (comment) TL;DR you can get that with roughly: type Tagged<T, Tag> = T & { __tag: Tag };
type DollarValue = Tagged<string, 'DollarValue'>;
const dollar: z.Schema<DollarValue> = z.number() as any; |
The major difficulty here is the TypeScript uses structural type rather than nominal typing so if something is structurally compatible, they are equivalent and the compiler doesn't treat them differently. This branding trick lies to the compiler and tells it that it has a special |
Branded types were added in the latest release: #1279 |
Is #3 (comment) still the recommended way to brand strings-only or is brand ok? I am using So I am using this as part of my API and later re-using that API type, only to get an error like:
I see the edit: I was using |
We use numbers all over our codebase to represent numbers, dollar value, percentages, etc. Ideally, we'd like to keep the zod type along with a typescript type that represents that type.
Here's an example:
Ideally, when using
z.infer<typeof dollarValueSchema>
we getDollarValue
type, instead ofnumber
.Thoughts?
The text was updated successfully, but these errors were encountered: