【问题标题】:Decorators and Private fields javascript装饰器和私有字段 javascript
【发布时间】:2021-12-14 21:22:59
【问题描述】:

我发现自己尝试使用带有原生 javascript 私有属性 (#) 的装饰器,而这些正在使用的第一个“识别”不起作用。

我通过在我的值对象的私有属性上使用 class-validator 装饰器来识别这一点。

我在代码编辑器中遇到的错误是:Decorators are not valid here

例子:

import { IsString } from 'class-validator';

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

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

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

【问题讨论】:

  • JS 中的私有字段是完全私有的,任何东西都无法从外部访问。因此,它们不能被装饰是有道理的——装饰器无法访问它们。

标签: javascript typescript decorator private class-validator


【解决方案1】:

按照 VLAZ 的建议进行操作:

JS 中的私有字段是完全私有的,任何东西都无法从外部访问。因此,它们不能被装饰是有道理的——装饰器无法访问它们。

这是完全正确的,所以当我仔细查看值对象时,我意识到它确实具有公共 get 属性,因此通过测试可以在这些属性上使用装饰器。

留下类似的东西:

import { IsString } from 'class-validator';

Class Person {
  #name: string;

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

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

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2012-11-12
    • 2021-10-10
    • 2018-06-17
    • 2014-02-20
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    相关资源
    最近更新 更多