Open Eyon42 opened 1 year ago
I have simplified the example to make it easier to diagnose. This seems like a bug, but it could also be a limitation of TypeScript.
const schema = z.object( { foo: z.number(), bar: z.string() } )
type Data = z.infer<typeof schema>
function someFn1<K extends keyof Data> ( key: K ) {
return schema.pick( { [ key ]: true } ).parse( 'anything' )[ key ]
}
someFn1( 'foo' ) // : number
someFn1( 'bar' ) // : string
function someFn2<K extends keyof Data> ( key: K ) {
return schema.shape[ key ].parse( 'anything' )
}
someFn2( 'foo' ) // : string | number
someFn2( 'bar' ) // : string | number
Is someone else able to explain what is happening here?
I have the same issue.
This is what happens:
A workaround (besides using the generic to manually set type) is using pick and then getting the value using the key:
But either way it's not expected behaviour.
Code example: