Open AmruthjithSunil opened 2 weeks ago
Before the if(!parsedData.data)
statement, the type of parsedData
can either be SafeParseSuccess
or SafeParseError
. However, after the if statement, it is resolved to SafeParseSuccess
, which means its error
property is undefined
. Therefore, in parsedData.error && console.error(parsedData.error)
, it's console
will not execute because the precondition is false.
Thanks for responding. But the type of parsed data is becoming never not SafeParseSuccess and why "const parsedError = parsedData.error; " line is not showing error.
You should hover over parsedData.error && ...
.
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing
My doubt is if optional key part of schema failed at that case there would be error value right. even though parsedData.data exist.
Which part do you mean?
Imagine if the schema had 3 keys. 2 required and 1 optional key. If optional key part of schema failed, I'll still get parsedData.data containing two required keys right? And I'll also get parsedData.error right? since optional key part failed.
After digging a bit deeper, I found it's more complicated than I initially thought.
I've simplified some code to explain, and I hope this will be helpful.
I suggest checking parsedData.success
instead of parsedData.data
. Since parsedData
is a discriminated union, using success
will provide a more accurate type check.
Thank you. My goal is to do console.warn if only optional part of schema fails and do console.error if required part fail. What is the recommended way to do this?
You can break the whole schema into requiredSchema
and optionalSchema
, no need to combine them togather.
Thank you. I'll do that.
const parsedData = getSuggestionsSchema.safeParse( action.payload?.data, ); if (!parsedData.data) { console.error("getSuggestions", parsedData.error); state.suggestions = initialState.suggestions; state.userMessage = initialState.userMessage; return; } const parsedError = parsedData.error; parsedError && console.warn(parsedError); parsedData.error && console.error(parsedData.error);
only in the last line inside the console error. Im getting error "Property 'error' does not exist on type 'never'"