zod icon indicating copy to clipboard operation
zod copied to clipboard

[Bug] Type inference does not work as expected when using catchall

Open egmacke opened this issue 3 years ago • 0 comments

Using zod's type inference (schema first approach) I get typescript errors when using catchall.

Example:

import z from 'zod';

const zschema = z
  .object({
    'main': z.string()
  })
  .catchall(z.number().optional());

const result = zschema.safeParse({
  'main': 'foo',
  'catch': 1
});

type Test = z.infer<typeof zschema>;
const foo: Test = {
  'main': 'foo',
  'a': 1
}

This example shows the expected behaviour for safeParse (which correctly validates the object), but it results in a typescript error when trying to instantiate an object using the infered type Test.

Expected behaviour:

type Test should resolve to something like:

{
  main: string,
  [x: string]?: number
}

However it produces the following error given the example above:

const foo: {
    [x: string]: number | undefined;
    main: string;
}
'foo' is declared but its value is never read.ts(6133)
Type '{ main: string; a: number; }' is not assignable to type '{ [x: string]: number | undefined; main: string; }'.
  Property ''main'' is incompatible with index signature.
    Type 'string' is not assignable to type 'number'.ts(2322)

egmacke avatar Aug 09 '22 11:08 egmacke