TypeScript 中的“extends A”和“extends typeof A”有什么区别?

jay*_*ubi 2 typescript

我正在制作一个类装饰器,我想限制这个装饰器只能应用于某些类,所以我这样做了:

@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) {}
}
Run Code Online (Sandbox Code Playgroud)

如果我将其更改function<T extends typeof A> (target:T) {}为,function<T extends A> (target:T) {}那么所有装饰器都会出错。

我不确定为什么我必须使用extends typeof A而不是extends A?它们之间有什么区别?

Ale*_*yne 5

用作类型时,类的名称表示该类的实例。要获取类构造函数的类型,可以使用typeof.

所以:

class A {}
const instance: A = new A()

const aConstructor: typeof A = A
const anotherInstance: A = new aConstructor()
Run Code Online (Sandbox Code Playgroud)

所以你的装饰器需要的原因typeof A是因为它在类构造函数上运行,而不是实例。

  • 这行代码 `const anotherInstance: new aConstructor()` 是什么意思?应该是“const anotherInstance: aConstructor”吗? (2认同)