8000 GitHub · Where software is built
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Interaction between zod and TypeScript handling of .catchall #1949
Closed
@ebroder

Description

@ebroder

zod seems to handle .catchall on an object differently than the corresponding TypeScript type it generates. Given the following schema:

const schema = z.object({
  foo: z.string(),
})
  .catchall(z.number());

zod will happily validate it:

schema.parse({ foo: 'hi', bar: 0 });

// ✅ no error

However, if you look at the corresponding inferred type:

type Schema = z.infer<typeof schema>;

// type Schema = {
//   [x: string]: number;
//   foo: string
// }

that type seems unsatisfiable directly in TypeScript:

const x: Schema = { foo: 'hi', bar: 0 };

// Type '{ foo: string; bar: number; }' is not assignable to type '{ [x: string]: number; foo: string; }'.
//   Property 'foo' is incompatible with index signature.
//     Type 'string' is not assignable to type 'number'.

I'm not entirely sure what the right behavior here is - should catchall require that all values on the shape be assignable to the catchall type? Is there some other way to declare what the output type is? (Is there some way to declare a constant of type Schema that TypeScript is happy with?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    staleNo activity in last 60 days

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0