简体   繁体   English

带有String的TypeScript简单装饰器

[英]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. 我正在学习typescript 1.5,我在尝试在我的房产上做一个简单的装饰时面临一个小问题。

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. 我的logMe函数记录了一个未定义的值。 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. 其次,由于您没有将任何参数传递给装饰器,因此您应该直接在Log函数上定义参数。

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: 现在,在运行您的方法时,它将输出I'm logged默认I'm logged

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() . 请注意,在执行此操作时,必须始终使用括号进行装饰: @Log() It doesn't give an error if you just do @Log . 如果你只做@Log它不会出错。 There is currently an open issue about this. 目前有一个公开的问题

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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