Skip to content

feature: Decorator-less support #2585

Open
@crutchcorn

Description

@crutchcorn

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions