我正在尝试构造自定义修饰符,例如,一个修饰符以验证字符串的最小长度。
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:我知道有一些用于数据验证的库,例如class-validator,但是,我想为验证和其他功能创建自定义装饰器。
我要去哪里错了?
答案 0 :(得分: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;
}