[英]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.