Skip to content

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

@ashuvssut

Description

@ashuvssut

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions