Skip to content

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

Description

@ManorSailor

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions