TypeScript simple decorator with string

I am learning typescript 1.5 and I am facing a small problem when trying to make a simple decorator on my property.

Actually, I need to enter a string inside my property when the application is running. Really simple, but I don't know how to handle. I have read a lot of examples, but nothing looks like what I need, just insert the string into your 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 value of undefined. I've never used a decorator before, so I need a really simple case.

Can you help me?

Achievements for promotion

+3


source to share


1 answer


First, the property decorator signature looks like this:

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

      

Modify the decorator according to this signature.

Second, since you are not passing any arguments to the decorator, you must define your parameters directly in the function Log

.

At this point, you can assign your string to the appropriate prototype property on which the decorator is defined. You should get the following:

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

      

Now, when you run 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 to understand it a little better, here's an example with arguments:

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

      

Remember that while you should always decorate the parentheses: @Log()

. It doesn't give an error if you just do @Log

. There is currently an open issue .

Playground

+1


source







All Articles