Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript class decorators - add class method

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?

like image 272
Alexey Savchuk Avatar asked Apr 09 '16 02:04

Alexey Savchuk


People also ask

What are class decorators in TypeScript?

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).

Are decorators still experimental in TypeScript?

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.

What is target in decorator TypeScript?

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.

How do you write a TypeScript decorator?

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.


1 Answers

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()

like image 68
Amid Avatar answered Sep 16 '22 15:09

Amid