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

Question - Encountering a TS error with ValidationOptions<U> in a middleware function #90

Open
ManorSailor opened this issue Jan 10, 2025 · 0 comments

Comments

@ManorSailor
Copy link

I'm writing a middleware for validating the request body, and I need to wrap the validator in a function. Here is my code:

import vine, { errors, type VineValidator } from "@vinejs/vine";
import type { SchemaTypes, ValidationOptions } from "@vinejs/vine/types";
import type { NextFunction, Request, Response } from "express";

function requireValidation<
  T extends SchemaTypes,
  U extends undefined | Record<string, any>
>(validator: VineValidator<T, U>, options?: ValidationOptions<U>) {
  // TODO: Find a way to make `options` optional
  return async (req: Request, res: Response, next: NextFunction) => {
    try {
      await validator.validate(req.body, options);
      next();
    } catch (error) {
      if (error instanceof errors.E_VALIDATION_ERROR) {
        res.status(400).send({
          status: "fail",
          message: error.message,
        });
      } else if (error instanceof Error) {
        res.status(500).send({
          status: "error",
          message: error.message,
        });
      }
    }
  };
}

export default requireValidation;

I receive the following error:
Argument of type '[ValidationOptions<U> | undefined]' is not assignable to parameter of type '[undefined] extends U ? [options?: ValidationOptions<U> | undefined] : [options: ValidationOptions<U>]'.ts(2345)

I don't know if this is the correct way to type this function either. I will appreciate some help!

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

1 participant