runtime schema is correct, but the inferred TypeScript type loses the conditional keys and enum values

21 hours ago 1
ARTICLE AD BOX

I have a createQuerySchema function that takes a config object with optional keys like fields and include.
I want the inferred type from z.infer<typeof schema> to include only the keys that were actually provided in the config, and for each included key to infer the correct enum union from the array values.

For example, with:

const querySchema = createQuerySchema({ fields: ["id", "status", "title"], });

I want:

type QueryType = { fields?: "id" | "status" | "title" | undefined; }

But I currently get:

type QueryType = { include?: unknown; fields?: unknown; }

Full code:

import { z } from "zod"; const createEnumSchema = <const T extends readonly [string, ...string[]]>( values: T ) => z.enum(values); const createQuerySchema = < const F extends readonly [string, ...string[]] | undefined, const I extends readonly [string, ...string[]] | undefined >(config: { fields?: F; include?: I; }) => { const shape = { ...(config.fields ? { fields: createEnumSchema(config.fields) } : {}), ...(config.include ? { include: createEnumSchema(config.include) } : {}), }; return z.object(shape); }; const querySchema = createQuerySchema({ fields: ["id", "status", "title"], }); type QueryType = z.infer<typeof querySchema>;

Thanks for help!

Read Entire Article