I'm in the midst of a TypeScript project where I am utilizing property decorators to impose validation on class properties. Below is a simplified version of the code I am working with:
Please note: Experimental decorators are enabled for this project.
interface ValidatorConfig {
[property: string]: {
[validatableProp: string]: string[]; // ['required', 'positive']
};
}
const registeredValidators: ValidatorConfig = {};
function Required(target: any, propName: string) {
registeredValidators[target.constructor.name] = {
[propName]: ['required']
};
}
function PositiveNumber(target: any, propName: string) {
registeredValidators[target.constructor.name] = {
[propName]: ['positive']
};
}
function validate(obj: any): boolean {
const objValidatorConfig = registeredValidators[obj.constructor.name];
if (!objValidatorConfig) {
return true;
}
let isValid = true;
for (const prop in objValidatorConfig) {
for (const validator of objValidatorConfig[prop]) {
switch (validator) {
case 'required':
isValid = isValid && !!obj[prop];
break;
case 'positive':
isValid = isValid && obj[prop] > 0;
break;
}
}
}
return isValid;
}
class Course {
@Required
title: string;
@PositiveNumber
price: number;
constructor(t: string, p: number) {
this.title = t;
this.price = p;
}
}
const createCourse = new Course("Hello Book", 1000);
if (!validate(createCourse)) {
alert('Invalid input, try again');
}
However, upon compiling my code using 'tsc app.ts', I encounter the following errors:
app.ts:57:4 - error TS1240: Unable to resolve signature of property decorator when called as an expression.
Argument of type 'ClassFieldDecoratorContext<Course, string> & { name: "title"; private: false; static: false; }' is not assignable to parameter of type 'string'.
57 @Required
~~~~~~~~
app.ts:59:4 - error TS1240: Unable to resolve signature of property decorator when called as an expression.
Argument of type 'ClassFieldDecoratorContext<Course, number> & { name: "price"; private: false; static: false; }' is not assignable to parameter of type 'string'.
59 @PositiveNumber
~~~~~~~~~~~~~~
How can I address the TS1240 errors associated with my property decorators?