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

Safer and better typings using z.output #16

Open
gpichot opened this issue Feb 16, 2024 · 1 comment
Open

Safer and better typings using z.output #16

gpichot opened this issue Feb 16, 2024 · 1 comment

Comments

@gpichot
Copy link

gpichot commented Feb 16, 2024

Hello,

In my projects I need to improve the typings as is does not always conform to what we get.

For instance using the schema:

z.object({
   value: z.number().default(10),
})

The type will be { value?: number | undefined } while the output type is :{ value: number }

In my code, I therefore use:

import {
  processRequest as zodProcessRequest,
  processRequestBody as zodProcessRequestBody,
  processRequestQuery as zodProcessRequestQuery,
  processRequestParams as zodProcessRequestParams,
} from 'zod-express-middleware'

export function processRequestBody<Schema extends z.ZodSchema<unknown>>(
  schema: Schema
): express.RequestHandler<ParamsDictionary, unknown, z.output<Schema>, unknown> {
  return zodProcessRequestBody(schema)
}

export function processRequestQuery<Schema extends z.ZodSchema<unknown>>(
  schema: Schema
): express.RequestHandler<ParamsDictionary, unknown, unknown, z.output<Schema>> {
  return zodProcessRequestQuery(schema)
}

export function processRequestParams<Schema extends z.ZodSchema<unknown>>(
  schema: Schema
): express.RequestHandler<z.output<Schema>, unknown, unknown, unknown> {
  return zodProcessRequestParams(schema)
}

export function processRequest<
  TParams extends z.ZodSchema<unknown>,
  TQuery extends z.ZodSchema<unknown>,
  TBody extends z.ZodSchema<unknown>
>(
  schemas: {
    params?: TParams
    query?: TQuery
    body?: TBody
  }
): express.RequestHandler<z.output<TParams>, unknown, z.output<TBody>, z.output<TQuery>> {
  return zodProcessRequest(schemas)
}

Do you think it would be possible to update the types to improve the typings?

I can create a PR if needed.

Best,
Gabriel

@sidonaldson
Copy link

In Zod v3.20 and above, the preferred way to get the output type of a schema is z.infer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants