简体   繁体   中英

Typescript Decorators before class instance

Iam playing around with Typescript decorators and everything is quite good working when I have instanciated a class. With the following code, my Class-decorator gets called: import { MyClass } from "./MyClass"; const myClass = new MyClass(); import { MyClass } from "./MyClass"; const myClass = new MyClass(); But when I dont instanciate the class explicit like in the example above, no decorators are called. For example, this module: https://github.com/xrobert35/es-mapping-ts relies on such a structure to save all classes in a storage and generate a mapping. I tried it without instanciating the classes first and generate a mapping, but it does not work either. Is there any Webpack or Typescript configuration that has to be set to get decorators executed before instanciating the classes where the decorators are placed? In my state of knowledge and in some online tutorials it is defined that class decorators are called when the class is defined and not when the class is instanciated. Cheers!

You can replace original class constructor with a class level decorator to do all kinds of cool stuff:

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

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