簡體   English   中英

Typescript - 我的屬性裝飾器不起作用,為什么?

[英]Typescript - My property decorator isn't working, why?

我正在嘗試構建自定義裝飾器,例如,一個裝飾器來驗證字符串的最小長度。

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:我知道有一些用於數據驗證的庫,例如類驗證器,但是,我想為驗證和其他功能創建自定義裝飾器。

我哪里錯了?

看起來您忘記導入裝飾器了。 假設您的結構如下:

- 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM