【问题标题】:Typescript - My property decorator isn't working, why?Typescript - 我的属性装饰器不起作用,为什么?
【发布时间】:2021-01-03 10:55:30
【问题描述】:

我正在尝试构建自定义装饰器,例如,用于验证字符串最小长度的装饰器。

function Min(limit: number) {
    return function (target: Object, propertyKey: string) {
        let value: string;
        const getter = function () {
            return value;
        };
        const setter = function (newVal: string) {
            if (newVal.length < limit) {
                Object.defineProperty(target, 'errors', {
                    value: `Your password should be bigger than ${limit}`
                });
            }
            else {
                value = newVal;
            }
        };
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter
        });
    }
}

在课堂上,我是这样称呼的:

export class User {

  @Min(8)
  password: string;
}

但是,我遇到了这个异常:

tslib_1.__decorate([
        ^

ReferenceError: Min is not defined
    at Object.<anonymous>

我的tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

PS:我知道有用于数据验证的库,例如类验证器,但是,我想为验证和其他功能创建自定义装饰器。

我哪里出错了?

【问题讨论】:

    标签: node.js typescript decorator nestjs


    【解决方案1】:

    您好像忘记导入装饰器了。假设您的结构如下:

    - decorator.ts
    - index.ts
    

    decorator.ts:

    export function Min(limit: number) {
      // ...
    }
    

    index.ts

    // Don't forget to import your decorator here
    import { Min } from './decorator';
    
    export class User {
    
      @Min(8)
      password: string;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2021-10-26
      • 2021-05-17
      • 2011-01-15
      • 2016-07-30
      相关资源
      最近更新 更多