Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript simple decorator with a String

I m studying typescript 1.5 and I m facing a little problem while trying to make a simple decorator on my property.

In fact, I need to inject a string inside my property when the app is running. Really simple, but I dont know how to process. I have read many example, but nothing looks at what I need, simply inject a string in my variable.

export class MyClass {

    @Log
        filePath:string;

    constructor() {

    }

    logMe() {
        console.log(this.filePath);
    }

}

function Log() {
    return function (target, key, descriptor) {
        console.log(target);
        console.log(key);
        console.log(descriptor);
        descriptor.Log = "I m logged";
        return descriptor;
    }
}

My logMe function logs me a undefined value. I ve never used decorator before, that's why I need a really simple case.

Can you help me ?

THanks for advance

like image 728
mfrachet Avatar asked Nov 20 '25 13:11

mfrachet


1 Answers

First, a property decorator's signature looks like this:

type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;

Change your decorator to match this signature.

Second, since you are not passing any arguments to the decorator, you should define your parameters directly on the Log function.

At this point, you can assign your string to the corresponding prototype property the decorator is defined on. You should end up with the following:

function Log(target: Object, propertyKey: string | symbol) {
    target[propertyKey] = "I'm logged";
}

Now when running your method, it will output I'm logged by default:

var c = new MyClass();
c.logMe(); // outputs: I'm logged
c.filePath = "test";
c.logMe(); // outputs: test

Playground


Just so you can understand this a bit better, here's an example with arguments:

function Log(defaultValue = "I'm logged") {
    return function (target: Object, propertyKey: string | symbol) {
        target[propertyKey] = defaultValue;
    };
}

Be aware though that when doing this you must always decorate with parentheses like so: @Log(). It doesn't give an error if you just do @Log. There is currently an open issue about this.

Playground

like image 180
David Sherret Avatar answered Nov 23 '25 02:11

David Sherret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!