zod icon indicating copy to clipboard operation
zod copied to clipboard

`fatal` missing from issue-type

Open Svish opened this issue 1 year ago • 0 comments

From my question asked on Discord:

When adding an issue (e.g. via ctx.addIssue in superRefine), you can set whether the issue is fatal or not:

    ctx.addIssue({
      code: 'custom',
      fatal: true, // Allowed
      params: {
        foo: 'bar',
      },
      path: [],
      message: 'Some message',
    });

But when manually creating a new ZodError with a matching issue, Typescript complains that fatal does not exist:

    const err = new z.ZodError([
      {
        code: 'custom',
        fatal: true, // Not allowed, with typescript-error below
        params: {
          foo: 'bar',
        },
        path: [],
        message: 'Some message',
      },
    ]);

Object literal may only specify known properties, and 'fatal' does not exist in type 'ZodCustomIssue & { message: string; }'

As mentioned in the reply to my question on Discord, there seems to be an oversight here. Is fatal is missing on ZodCustomIssue or ZodIssueBase, or is it "correct" that it doesn't exist there? I'm guessing not, since the fatal field does come back out on an issue when a fatal issue is created. Typewise, it seems to only be added to IssueData, which is the type ctx.addIssue accepts?


The reason why I ran into this, is because I have written a few "custom schemas" for often used "types", for re-use throughout my code-base, and to make sure they're done correctly, I've written some unit-tests for them:

    it('invalid should generate expected issue', () => {
      expect(AccountNumberSchema.safeParse('1234 56 78907')).toEqual({
        success: false,
        error: new z.ZodError([
          {
            code: 'custom',
            fatal: true, // Gives TS error, as mentioned
            params: {
              code: 'invalid_type',
              expected: 'account_number',
            },
            path: [],
            message: 'must be a valid account number',
          },
        ]),
      });
    });

Svish avatar Sep 13 '22 08:09 Svish