colinhacks / zod

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

Using generic schemas from generic functions makes enum fields optional #3704

Open lantw44 opened 3 months ago

lantw44 commented 3 months ago

Reopen https://github.com/colinhacks/zod/issues/995.

import { z } from 'zod';

function makeSchema<T extends string>(values: readonly [T, ...T[]]) {
  return z.object({
    e: z.enum(values),
    s: z.string(),
  });
}

function useSchema<T extends string>(values: readonly [T, ...T[]], input: unknown): void {
  const schema = makeSchema(values);
  const result = schema.parse(input);
  let { e, s } = result;
  s = e;
}

e is a string enum. s is a string. e should be assignable to s, but TypeScript disagrees:

zod.ts:14:3 - error TS2322: Type 'addQuestionMarks<baseObjectOutputType<{ e: ZodEnum<[T, ...T[]]>; s: ZodString; }>, any>["e"] | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'.

14   s = e;
     ~

e is declared as a required field. It can't be undefined.