colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Issue: z.any() and z.unknown() are optional by the default. #3730

Open oyershov opened 3 weeks ago

oyershov commented 3 weeks ago

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)

Screenshot 2024-08-29 at 10 52 37

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
}
sunnylost commented 3 weeks ago

I found the relevant code, and since they used undefined extends T, if they had used assertEqual<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

brupxxxlgroup commented 1 week ago

I have the same issue