简体   繁体   中英

Dynamic extends class in a typescript annotation

Suppose I have 2 class, A and B. I want to create a typescript annotation that does the same thing that extends class dynamically. I cannot use extends because the class A is only known at runtime.So in the result I want class A extends B {} But with A dynamic.

I have tried to create an annotation :

function extendsWithB(target) {
  //do something to extends the target with B class
  return target;
}

This could be use like that:

 @extendsWithB
   Class A {}

Any idea about what should I put in my annotation?

Edit: this question is purely theorical. I don't want to try this in production or something else.

I think you can get similar to the desired effect by doing something like this:

export function Ext(bCtor: any) 
{
    return (aCtor: any) => 
    {
        Object.getOwnPropertyNames(bCtor.prototype).forEach(name => {
            aCtor.prototype[name] = bCtor.prototype[name];
        });
    }
}

And apply it:

@Ext(B)
class A
{
    //...
}

Of course no more type checks as typescript does not know about this hack.

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