我做了一個類裝飾器,我想限制這個裝飾器只能應用于某些類,所以我做了:
@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) {}
}
如果我把function<T extends typeof A> (target:T) {}
改成function<T extends A> (target:T) {}
,那么所有的裝飾器都會變成錯誤。
我不知道為什么我要用extends typeof A
而不是extends A
?它們之間有什么區別?
當用作類型時,類的名稱表示該類的實例。要獲得類構造函數的類型,可以使用
typeof
。So:
因此,您的decorator需要
typeof A
的原因是它在類構造函數上操作,而不是在實例上操作。