[英]Typescript - My property decorator isn't working, why?
I'm trying to construct custom decorators, for example, a decorator to validate the minimum length of a string.我正在尝试构建自定义装饰器,例如,一个装饰器来验证字符串的最小长度。
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
});
}
}
In the class, I'm calling this way:在课堂上,我这样称呼:
export class User {
@Min(8)
password: string;
}
However, I'm getting this exception:但是,我收到此异常:
tslib_1.__decorate([
^
ReferenceError: Min is not defined
at Object.<anonymous>
My tsconfig.json:
我的
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: I know there are libraries, for data validations, like the class-validator, however, I would like to create custom decorators for validations and other features. PS:我知道有一些用于数据验证的库,例如类验证器,但是,我想为验证和其他功能创建自定义装饰器。
Where am I going wrong?我哪里错了?
It looks like you forgot to import your decorator.看起来您忘记导入装饰器了。 Assuming your structure as following:
假设您的结构如下:
- decorator.ts
- index.ts
In decorator.ts
:在
decorator.ts
:
export function Min(limit: number) {
// ...
}
In the index.ts
:在
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.