Reputation: 2212
I was make a class decorator and I wanted to limit this decorator could only be applied to certain classes so I did:
@decorator()
class A {
foo:string;
}
@decorator()
class B extends A {
}
@decorator()
class C {}
function decorator () {
// This makes decorators work on class A and B except class C
return function<T extends typeof A> (target:T) {}
// This makes decorators become error on all the classes
// return function<T extends A> (target:T) {}
}
If I changed the function<T extends typeof A> (target:T) {}
into function<T extends A> (target:T) {}
then all the decorators would became errors.
I'm not sure why do I have to use extends typeof A
instead of extends A
? And what's the difference between them?
Upvotes: 2
Views: 396
Reputation: 187144
The name of class when used as a type means instances of that class. To get the type of a class constructor, you use typeof
.
So:
class A {}
const instance: A = new A()
const aConstructor: typeof A = A
const anotherInstance: A = new aConstructor()
So the reason that your decorator requires typeof A
is because it operates on a class constructor, and not instances.
Upvotes: 5