zod: Field becomes optional when value is any or unknown
const s = z.object({ x: z.unknown() })
type s = z.infer<typeof s>
// s has { x?: unknown } but should be { x: unknown }
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 15
- Comments: 20 (6 by maintainers)
This is the best I’ve got:
{ a: unknown }and{ a?: unknwon}is differentError
Type '{ test?: unknown; }' is not assignable to type 'TestType'. Property 'test' is optional in type '{ test?: unknown; }' but required in type 'TestType'.Isn’t that the purpose of
z.record?Possible today:
Proposal:
Intuitively, when writing typescript, you’d use
Record<string, any>orRecord<string, unknown>for such use case.How does one write
anything but something must be passed in and it cannot be undefined?I’d say this is intentional for the moment. Currently Zod can’t really differentiate between
{arg: string | undefined}and{arg?: string | undefined}. When you pass a key schemaSs.t.undefined extends infer<typeof S>, Zod will add the question mark. In this caseundefinedextendsunknown(because everything does), hence the question mark. This also agrees with runtime behavior:The broader question of how/whether to provide an API that differentiates between different types of optionality is tracked here: https://github.com/colinhacks/zod/issues/635
It infers to
object- which is a standard TypeScript type for object and makes sense in this situation.These type assertions seem to be correct to me:
In the code, I’ve made sure the “output” type is
objectin this case- so yea, its not quite the same as passing in{}and making it"passthrough"- there was a little more involved.I came up to this object schema definition
It removes question marks magic, so you can use it like this