We see that when we specify a conditional for when the parse is successful, the type of parsed is narrowed. We specify another conditional inside of that for when the API result passed === true, and the type is narrowed further to one where the value key is present.
Let's say we want to make foo generic so that we can potentially return the parsed API response value.
Now we have specified that subSchema is of a type TSubSchema, which is an extension of ZodTypeAny.
But we get an error on the line
console.log(parsed.data.value);
indicating that
Property 'value' does not exist on type '{ [k in keyof addQuestionMarks<baseObjectOutputType<{ passed: ZodLiteral<true>; value: TSubSchema; }>, any>]: addQuestionMarks<baseObjectOutputType<{ passed: ZodLiteral<...>; value: TSubSchema; }>, any>[k]; } | { ...; }'.
Property 'value' does not exist on type '{ passed: false; msg: string; }'.ts(2339)
This tells that us that the type narrowing is not working, as it the type checker is complaining about value potentially not being a key of parsed.data.
If we use
zod
to parse an API response:We see that when we specify a conditional for when the parse is successful, the type of
parsed
is narrowed. We specify another conditional inside of that for when the API resultpassed === true
, and the type is narrowed further to one where thevalue
key is present.Let's say we want to make
foo
generic so that we can potentially return the parsed API response value.Now we have specified that subSchema is of a type
TSubSchema
, which is an extension ofZodTypeAny
.But we get an error on the line
indicating that
This tells that us that the type narrowing is not working, as it the type checker is complaining about
value
potentially not being a key ofparsed.data
.