如何解决打字稿-我的资产装饰器无法正常工作,为什么?
我正在尝试构造自定义修饰符,例如,一个修饰符以验证字符串的最小长度。
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,但是,我想为验证和其他功能创建自定义装饰器。
我要去哪里错了?
解决方法
您似乎忘记了导入装饰器。假设您的结构如下:
- 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。