【问题标题】:Typescript Decorators before class instance类实例之前的打字稿装饰器
【发布时间】:2020-05-31 07:03:19
【问题描述】:

我正在玩 Typescript 装饰器,当我实例化一个类时,一切都很好。 使用以下代码,我的 Class-decorator 被调用: import { MyClass } from "./MyClass"; const myClass = new MyClass(); 但是当我不像上面的例子那样显式地实例化类时,不会调用任何装饰器。例如,这个模块:https://github.com/xrobert35/es-mapping-ts 就依赖这样的结构将所有类保存在一个存储中并生成一个映射。我在没有先实例化类并生成映射的情况下尝试了它,但它也不起作用。 在实例化放置装饰器的类之前,是否必须设置任何 Webpack 或 Typescript 配置才能执行装饰器? 根据我的知识和一些在线教程,定义类装饰器是在定义类时调用,而不是在实例化类时调用。 干杯!

【问题讨论】:

  • 装饰器在方法(或实例化)发生时调用,而不是在定义时调用。

标签: typescript webpack decorator typescript-decorator reflect-metadata


【解决方案1】:

你可以用类级别的装饰器替换原来的类构造器来做各种很酷的事情:

function example(target: any) {
    // save a reference to the original constructor
    const original = target;

    // the new constructor behaviour
    const f: any = function (...args: any[]) {
        console.log("Hook before original constructor...");

        const newArgs = [...args].reverse();

        const instance = new original(...newArgs);

        console.log("Hook after original constructor...");

        instance.d = 'ddd';

        return instance;
    }

    // copy prototype so intanceof operator still works
    f.prototype = original.prototype;

    // return new constructor (will override original)
    return f;
}

@example
class SomeClass {
    constructor(public a: number, public b: number, public c: number) {
        console.log("Hello from constructor!")
    }
}

const instance1 = new SomeClass(1, 2, 3);
console.log(instance1); // SomeClass {a: 3, b: 2, c: 1, d: "ddd"}

Link to playground

【讨论】:

  • 我知道我可以用装饰器做什么,但以你为例:是否可以运行类装饰器(例如,将类保存到内部类映射的装饰器)没有实例化类?我希望我的所有类名都通过装饰器在内部保存,但我不想实例化所有可能的请求......但无论如何感谢这个例子!
  • 类级别的装饰器在类被“声明”时运行。此时有一个用于替换构造函数/方法、保存元数据等的窗口......
  • 那么没有分析器可以分析装饰器的所有类吗?总之:我必须自己调用所有类,所以当我想在请求进入之前调用所有类的所有 Classdecorator 时,这个过程不能动态化?
  • 正如我之前所说。类级别的装饰器只运行一次。当类被声明时(不是在实例创建时)。因此,即使您从未构建过任何实例,您也可以注册装饰类名称。例如:typescriptlang.org/play/…
  • 谢谢!当所有类都在外部文件中声明时?所以至少应该进口?
猜你喜欢
  • 2018-02-12
  • 1970-01-01
  • 2021-09-30
  • 2015-06-28
  • 2018-04-28
  • 2016-12-05
  • 1970-01-01
  • 2020-01-02
  • 2020-12-03
相关资源
最近更新 更多