zod: Issue: z.any() and z.unknown() are optional by the default.
Hello👋,
I face an issue with the default behavior of z.any() and z.unknown() schemas. I expect these fields to have consistant behavior in line with other supported schemes: required after the type is inferred. The actual result is that these fields are optional.
Question: Is the current behavior expected or is it a bug?
Unit test coverage that misses this case: https://github.com/colinhacks/zod/blob/main/src/__tests__/object.test.ts#L292
Type inference example (screenshot)
Code example:
import { z } from 'zod';
/**
* Replace `z.any()` with the appropriate Zod schemas.
* @see {myConfig}, @see {myQuery}, @see {myQueryResult}
*/
const mySchema = z.object({
myConfig: z.any(),
myQuery: z.any(),
myQueryResult: z.unknown(),
hasRestrictedFields: z.boolean(),
})
type MyDTO = z.infer<typeof mySchema>
export {
mySchema,
MyDTO
}
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 4
- Comments: 19
this is actually a valid workaround - really appreciate your efforts @darky and @sunnylost 😃 really think, there should be a zod-way of doing that though.
z.custom<Required<unknown>>(x => x !== undefined)z.custom<Required<any>>(x => x !== undefined)Maybe ☝️ is ok
Workaround from another thread https://github.com/colinhacks/zod/issues/1628#issuecomment-1338136697
I found the relevant code, and since they used
undefined extends T, if they had usedassertEqual<undefined, T>, the optional situation wouldn’t have occurred. So I believe this was intentional.https://github.com/colinhacks/zod/blob/8552233c77426f77d3586cc877f7aec1aa0aa45b/src/helpers/util.ts#L107-L109