本文介绍了如何将实例变量传递给TypeScript装饰器参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是一个很好的例子

考虑以下情况,

class MyClass {
    @enumerable(false)
    get prop() {
        return true;
    }

    @property({required: true}) //here pass constant is no issue
    public startDateString:string;

    @property({afterDate: this.startDateString}) //how to pass startDateString here?
    public endDateString:string;
}

function enumerable(isEnumerable: boolean) {
    return (target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
        descriptor.enumerable = isEnumerable;
        return descriptor;
    };
}

我尝试了所有操作,但似乎没有办法通过 startDateString 进入装饰器参数。 startDateString 可以是变量,函数和引用。

I tried everything but it seems I have no way to pass startDateString into decorator argument. startDateString could be a variable, a function and a reference.

推荐答案

在声明类时,装饰器将被调用,此时没有实例可传递到装饰器中。

Decorators get called when the class is declared and at this time there is no instance to pass into the decorator.

例如,使用以下代码:

class MyClass {
    startDateString: string;
    @property({ afterDate: this.startDateString })
    endDateString: string;
}
let myClass = new MyClass();




  1. MyClass

  2. 装饰器在 MyClass 上运行。此时没有实例可以传入,装饰器参数中的 this 指向全局对象,而不是实例。

  3. new MyClass()被调用并创建实例。在此步骤中,装饰器不会被调用。

  1. MyClass is declared.
  2. The decorators are run on MyClass. There is no instance that exists to pass in at this point and this in the decorator argument refers to the global object—not an instance.
  3. new MyClass() is called and the instance is created. Decorators aren't called on this step. That already happened.

看一下已编译的JavaScript以供参考:

Take a look at the compiled JavaScript for reference:

var MyClass = (function () {
    // -- 1 --
    function MyClass() {
    }
    // -- 2 --
    __decorate([
        // see here... `this` is equal to the global object
        property({ afterDate: this.startDateString })
    ], MyClass.prototype, "endDateString", void 0);
    return MyClass;
})();
// -- 3 --
var myClass = new MyClass();

请注意,使用 this.startDateString 不会'不会在这里抛出编译错误,因为 this 被键入为 any

Note that using this.startDateString doesn't throw a compile error here because this is typed as any.

因此,通过传入实例属性来尝试执行的操作没有意义,也是不可能的。

So what is trying to be done here by passing in an instance property doesn't make sense and isn't possible.

您可以做的是make startDateString 静态,然后像这样传递它: @property({afterDate:MyClass.startDateString})

What you could do is make startDateString static then pass it in like so: @property({ afterDate: MyClass.startDateString }).

这篇关于如何将实例变量传递给TypeScript装饰器参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 12:45