Skip to content

Exercise 14: incorrect return type passes #2

@c-ehrlich

Description

@c-ehrlich

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>>
  >
>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions