colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.39k stars 1.15k forks source link

Incompatibility with TypeScript 5.1.3 - discriminatedUnion #2523

Open sawden opened 1 year ago

sawden commented 1 year ago

Description

I recently updated TypeScript from version 4.9.5 to 5.1.3 and I noticed that my code that uses zod is no longer working as expected. It seems that types are not being correctly extracted when using TypeScript 5.1.3.

Code to reproduce the issue

Here is the code in which I define a zod type:

import * as z from 'zod';

export const ZApiGatewayClientSchema = z.enum(['One', 'Two']);

const ZGetExampleBySelectorInputSchemaOne = z.object({
  gateway: z.literal(ZApiGatewayClientSchema.Enum.One),
  env: ZApiEnvironmentSchema,
  language: z.string().length(2).optional(),
  brand: z.string().optional(),
  bookingSystem: ZBookingSystemSchemaLegacy.optional(), // optional
});

const ZGetExampleBySelectorInputSchemaTwo = z.object({
  gateway: z.literal(ZApiGatewayClientSchema.Enum.Two),
  env: ZApiEnvironmentSchema,
  language: z.string().length(2).optional(),
  brand: z.string().optional(),
  bookingSystem: ZBookingSystemSchemaLegacy, // required
});

export const ZGetExampleBySelectorInputSchema = z.discriminatedUnion('gateway', [
  ZGetExampleBySelectorInputSchemaOne,
  ZGetExampleBySelectorInputSchemaTwo,
]);

export type TGetExampleBySelectorInputSchema = z.infer<
  typeof ZGetExampleBySelectorInputSchema
>;

And here is the code in which I attempt to extract the discriminated union using Extract:

async getExampleBySelector(
  input: Extract<TGetExampleBySelectorInputSchema, { gateway: 'One' }>,
): Promise<ApiExampleResponseOne> {
  return await this.requestHotels(input);
}

This code worked correctly with TypeScript 4.9.5, but after updating to TypeScript 5.1.3, the types are not extracted correctly.

Expected behavior

The types should be correctly extracted even after updating TypeScript to version 5.1.3.

Actual behavior

The types are not correctly extracted after updating to TypeScript 5.1.3.

Environment:

stale[bot] commented 1 year ago

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.

JacobWeisenburger commented 1 year ago

Please send a full reproducible code example.

image image image