我想创建一个可以选择接受参数的字段装饰器。
该参数应包含以下任意值:无、布尔值或函数。
我知道如何做到这一点,但我对结果并不是 100% 满意:
export class TestClass{
@Required(isRequired)
public testField: string;
}
export function isRequired():boolean{
... some validation logic, maybe depending on other fields...
return result;
}
@Required 的实现:
export function Required(expression?: boolean|Function): Function {
return (target: any, key: string) => {
if (expression === null || typeof expression == 'undefined') {
expression = true;
}
console.log("Required found: " + expression, ":", target, key);
... register the field and its validation expression for later usage
}
}
所以这工作正常,但是当我不想添加表达式(因此使用默认的“true”表达式)时,我希望能够像这样编写它:
class TestClass{
@Required
public testField: string;
}
我收到 TypeScript 错误 (TS1240),内容如下:
作为属性调用时无法解析属性装饰器的签名
表达。提供的参数与调用的任何签名都不匹配
目标
所以我需要写@Required()
class TestClass{
@Required()
public testField: string;
}
是否可以编写一个装饰器实现,它可以选择接受一个参数,并且当未指定该参数时,不需要添加“()”?