Created
September 5, 2024 09:15
-
-
Save huksley/7d8c800d22cf5fa423e277ddc745a92f to your computer and use it in GitHub Desktop.
Zod do not plays well with default? catch?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { ZodSchema } from "zod"; | |
// eslint-disable-next-line no-duplicate-imports | |
import { z } from "zod"; | |
// Define a Zod schema | |
const userSchema = z.object({ | |
// Fix 1. Do not use catch - wreks the input type https://github.com/colinhacks/zod/issues/2852 | |
// Fix 2. Use optional() before default(), don't use at all??? | |
page: z.number().default(1), | |
sort: z.string().optional(), | |
sortOrder: z.string().optional(), | |
name: z.string().optional(), | |
age: z.number().optional(), | |
}); | |
const extendedUserSchema = userSchema.extend({ | |
email: z.string().email().optional(), | |
}); | |
// Infer the type from the schema | |
export type User = z.infer<typeof userSchema>; | |
export type ExtendedUser = z.infer<typeof extendedUserSchema>; | |
// Error: The types of '_input.page' are incompatible between these types. | |
// Type 'number | undefined' is not assignable to type 'number'. | |
const t: ZodSchema<ExtendedUser> = extendedUserSchema; | |
console.log(t); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment