Skip to content

Trouble with return type of generic funcion #2858

Closed Answered by datenreisender
datenreisender asked this question in Q&A
Discussion options

You must be logged in to vote

Since asking my question, the documentation has been supplemented by the section Inferring the inferred type, which describes a solution.

With it your myFetch can also be shortened to this:

async function myFetch<T extends z.ZodTypeAny>(url: string, schema: T) {
    const resp = await fetch(url);
    const json = await resp.json();
    return schema.parse(json) as z.infer<T>;
}

My original problematic code can be enhanced by changing the return result to return result as z.SafeParseSuccess<z.infer<T>>

Thanks for your input and reminding me of this question.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by datenreisender
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants