Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

discriminatedUnion produces TS error when .default or .preprocess are applied #1263

Closed
RobertCraigie opened this issue Jul 14, 2022 · 2 comments
Labels
stale No activity in last 60 days

Comments

@RobertCraigie
Copy link

Playground link.

Given this snippet:

import { z } from 'zod';

const FooSchema = z.object({
  type: z.literal('foo').default('foo'),
  a: z.string(),
});

const BarSchema = z.object({
  type: z.literal('custom'),
  method: z.string(),
});

const BazSchema = z.discriminatedUnion('type', [FooSchema, BarSchema]);
console.log(BazSchema.parse({ a: 'foo' }));

TypeScript produces this error:

$ tsc tmp.ts
tmp.ts:13:49 - error TS2322: Type 'ZodObject<{ type: ZodDefault<ZodLiteral<"foo">>; a: ZodString; }, "strip", ZodTypeAny, { type?: "foo"; a?: string; }, { type?: "foo"; a?: string; }>' is not assignable to type 'ZodDiscriminatedUnionOption<"type", Primitive>'.
  Type '{ type: z.ZodDefault<z.ZodLiteral<"foo">>; a: z.ZodString; }' is not assignable to type '{ type: ZodLiteral<Primitive>; } & ZodRawShape'.
    Type '{ type: z.ZodDefault<z.ZodLiteral<"foo">>; a: z.ZodString; }' is not assignable to type '{ type: ZodLiteral<Primitive>; }'.
      Types of property 'type' are incompatible.
        Property 'value' is missing in type 'ZodDefault<ZodLiteral<"foo">>' but required in type 'ZodLiteral<Primitive>'.

13 const BazSchema = z.discriminatedUnion('type', [FooSchema, BarSchema]);
                                                   ~~~~~~~~~

  node_modules/zod/lib/types.d.ts:531:9
    531     get value(): T;
                ~~~~~
    'value' is declared here.


Found 1 error in tmp.ts:13

This code works at runtime however and Zod correctly parses the object:

{ type: 'foo', a: 'foo' }
@stale
Copy link

stale bot commented Sep 12, 2022

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale No activity in last 60 days label Sep 12, 2022
@stale stale bot closed this as completed Sep 20, 2022
@RobertCraigie
Copy link
Author

RobertCraigie commented Oct 12, 2022

Bump for stale bot - I'd still like to have this feature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stale No activity in last 60 days
Projects
None yet
Development

No branches or pull requests

1 participant