Search code examples
javascripttypescriptdecoratorprivateclass-validator

Decorators and Private fields javascript


I find myself trying to use decorators with the native javascript private properties (#) and these first 'recognize' that are in use do not work.

I identified this by using the class-validator decorators on the private properties of my value objects.

The error I get in my code editor is: Decorators are not valid here

Example:

import { IsString } from 'class-validator';

Class Person {
  @IsString()
  #name: string;

  constructor(name: string) {
    this.#name = name;
  }

  get name(): string {
    return this.#name;
  }
}

Solution

  • Okey as suggested by VLAZ:

    Private fields in JS are completely private and inaccessible to anything from outside. Thus it makes sense they cannot be decorated - there is no way for the decorator to access them.

    This is completely correct, so when I took a closer look at the value object I realized that it does have public get properties, so by testing it is possible to use decorators on those properties.

    Leaving something like:

    import { IsString } from 'class-validator';
    
    Class Person {
      #name: string;
    
      constructor(name: string) {
        this.#name = name;
      }
    
      @IsString()
      get name(): string {
        return this.#name;
      }
    }