How to define property with TypeScript and decorators?
For example I have this class decorator:
function Entity<TFunction extends Function>(target: TFunction): TFunction {
Object.defineProperty(target.prototype, 'test', {
value: function() {
console.log('test call');
return 'test result';
}
});
return target;
}
And use it:
@Entity
class Project {
//
}
let project = new Project();
console.log(project.test());
I have this console log:
test call entity.ts:5
test result entity.ts:18
This code correctly worked, but tsc return error:
entity.ts(18,21): error TS2339: Property 'test' does not exist on type 'Project'.
How to fix this error?
A Class Decorator is declared just before a class declaration. The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition. A class decorator cannot be used in a declaration file, or in any other ambient context (such as on a declare class).
As of writing this guide, decorators are still an experimental feature in TypeScript. To enable this feature, set the experimentalDecorators compiler flag either on the command line or in your tsconfig. json file.
target: Constructor function of the class if we used decorator on the static member, or prototype of the class if we used decorator on instance member. In our case it is firstMessage which is an instance member, so the target will refer to the prototype of the Greeter class. propertyKey: It is the name of the property.
In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.
Af far as I know for now this is not possible. There is a discussion on this issue here: issue.
So you either do not use decorators to extend classes, and maybe if appropriate use interfaces with declaration merging to extend type declaration. Or use type assertion (but loosing type checks): (<any>project).test()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With