Avraam Mavridis Avraam Mavridis - 1 month ago 25
TypeScript Question

Type 'any' is not a constructor function type

I am trying to implement a class decorator in Typescript. So I have a function that takes a class as an argument.

const decorate = function ()
{
return function ( target: any )
{
return class myExtendClass extends target{}
};
};


The goal is to use it like:

@decorate()
class Something{}


Unfortunately I am getting
type any is not a constructor function type
. Any idea how I can achieve what I want?

Answer

my question is why this code doesnt work, since its valid js

That depends on what you mean by doesn't work.

The generated javascript is valid and will work. But TypeScript is much stricter and will complain if you write code that does not comply with the rules of TS, even it often will play nice and give you the compiled js anyway.

The problem with what you are trying to do is that TS does not have support for extending classes via decorators. It will produce js that works, but TS does not understand what is happening when you do this.

For example:

const decorate = () => (target: typeof Cat) =>
{
    return class Lion extends target
    {
        public Roar = () => console.log("Roaar")
    }
}

@decorate()
class Cat
{
    public Purr = () => console.log("Purr purr");
}

var lion = new Cat();
lion.Roar(); // Error in TypeScript but working in js

This works when you run it, but TS does not understand what you are doing within the decorator, so it don't know that the class Cat actually is a Lion.

There is a feature request about making TS understand class mutations in decorators, but at this time it's not supported.

I suggest that you avoid mutating classes in decorators like this. And even if it would work, I don't see the point in your example as it is now, it's not very intuitive and if you want all Something to have certain properties you could just extend it directly: Something extends MyReusableProperties

Comments