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

feature: Decorator-less support #2585

Open
crutchcorn opened this issue Feb 27, 2025 · 0 comments
Open

feature: Decorator-less support #2585

crutchcorn opened this issue Feb 27, 2025 · 0 comments
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.

Comments

@crutchcorn
Copy link

Description

I'm looking to run a project in Node.js' built-in TypeScript --strip-types support as of Node 23+.

However, this requires us to set experimentalDecorators to false, which causes my project utilizing class-validator to fail (understandably).

Proposed solution

What if, without modifying any existing source code, we could enable the following decorator-less validation API:

class MyClass {
  someProperty: string;
}

addValidators(MyClass, {
  someProperty: Contains('hello', {
    message: '$value is not valid. Your string must contain a hello word',
  }),
});

Using the following source code addition:

interface Constructable {
  new (...args: any[]): any;
}

/**
 * Only checks the keys of the first layer of the object, does not support nested objects' keys being validated independently
 *
 * Only proxies the first layer of the object
 */
export function addValidators<
  TBaseObj extends Constructable,
  TSchema extends {
    [key in keyof InstanceType<TBaseObj>]?: PropertyDecorator;
  }
>(baseObj: TBaseObj, schema: TSchema) {
  const keys: Array<keyof TSchema> = Object.keys(schema) as Array<keyof TSchema>;

  keys.forEach(key => {
    schema[key]?.call(baseObj, baseObj, key as string);
  });
}

I did some initial testing and it seems to work as expected, while enforcing the types match up between the baseObj and schema.

I know this is a radical idea, but it would help us migrate to a better TypeScript running behavior while allowing us to continue using class-validator

@crutchcorn crutchcorn added flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features. labels Feb 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
flag: needs discussion Issues which needs discussion before implementation. type: feature Issues related to new features.
Development

No branches or pull requests

1 participant