Im working on a TypeScript project where I’m using property decorators to enforce validation on class properties. Here’s a simplified version of my code:
Note: Experimental decorators have been turned on in 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, when I compile my code using ‘tsc app.ts’, I get 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 resolve the TS1240 errors with my property decorators?
Rana Zuhair is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
From the docs…
Decorators are a language feature which hasn’t yet been fully ratified into the JavaScript specification
You need to enable the experimentalDecorators
option in your tsconfig.json
.
If go to this TSPlayground, your code works as expected. Disable the experimentalDecorators
option and it fails with the errors you mention above.