class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

fix: `Type 'undefined' is not assignable to type 'ValidationOptions'.` when creating validation decorators

Open ashuvssut opened this issue 3 years ago • 0 comments

I am creating a custom class validator using class-validator package. https://github.com/typestack/class-validator#custom-validation-classes

import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from "class-validator";

import { User } from "../../../entity/User";

@ValidatorConstraint({ async: true })
export class IsEmailAlreadyExistConstraint implements ValidatorConstraintInterface{
  validate(email: string) {
    return User.findOne({ where: { email } }).then(user => {
      if (user) return false;
      return true;
    });
  }
}

export function IsEmailAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsEmailAlreadyExistConstraint,
    });
  };
}

I am getting this error

(property) ValidationDecoratorOptions.propertyName: string
Target object's property name to be validated.

Argument of type '{ target: Function; propertyName: string; options: ValidationOptions | undefined; constraints: never[]; validator: typeof IsEmailAlreadyExistConstraint; }' is not assignable to parameter of type 'ValidationDecoratorOptions' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'options' are incompatible.
    Type 'ValidationOptions | undefined' is not assignable to type 'ValidationOptions'.
      Type 'undefined' is not assignable to type 'ValidationOptions'.

enter image description here

Solution when creating custom class validators, validationOptions can not be undefined. It gives off this error: Type 'undefined' is not assignable to type 'ValidationOptions'.

so the validationOption argument from custom validation decorator functions should not allowed to be optional.

ashuvssut avatar May 10 '22 08:05 ashuvssut