zod-tutorial icon indicating copy to clipboard operation
zod-tutorial copied to clipboard

Exercise 14: incorrect return type passes

Open c-ehrlich opened this issue 3 years ago • 0 comments

Currently both of these "solutions" pass exercise 14:

// correct
const genericFetch = <Schema extends z.ZodSchema>(
  url: string,
  schema: Schema
): Promise<z.infer<Schema>> => {
  return fetch(url)
    .then((res) => res.json())
    .then((result) => schema.parse(result));
};
// incorrect, doesn't return a promise
const genericFetch = <Schema extends z.ZodSchema>(
  url: string,
  schema: Schema
): z.infer<Schema> => {
  return fetch(url)
    .then((res) => res.json())
    .then((result) => schema.parse(result));
};

This is because the current test case checks the type of result, which awaits genericFetch, so it doesn't care if genericFetch returns a Promise or not.

I came up with two possibilities for a test case that catches this - I don't love either of these, maybe a TS Wizard could come up with something more elegant.

  1. Just check that genericFetch returns a promise of some sort
Expect<Equal<ReturnType<typeof genericFetch>, Promise<z.TypeOf<any>>>>
  1. Check the entire type of genericFetch
Expect<
  Equal<
    typeof genericFetch,
    <Schema extends z.ZodType<any, z.ZodTypeDef, any>>(
      url: string,
      schema: Schema
    ) => Promise<z.TypeOf<Schema>>
  >
>

c-ehrlich avatar Sep 06 '22 12:09 c-ehrlich