简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM