<T extends { new(...args: any[]): {} }>(constructor:T) 在打字稿中是什么意思?

Jac*_*len 1 typescript

每个打字稿装饰器都需要定义这个?这是什么意思?为什么不在打字稿语言中设置这个默认值或开发人员每次都需要编写这个。

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {}
Run Code Online (Sandbox Code Playgroud)

小智 5

装饰器需要一个包含构造函数的对象作为参数。这个对象可以实例化不同的类,这就是你必须使用泛型函数的原因。这就是为什么您需要一个看起来像这样的函数,function classDecorator<T>(constructor:T) {} 其中 T 被类或类型替换。例如,您可以像这样调用函数:(classDecorator<MyClass>(myClass) 在此处查看有关泛型的更多信息:https : //www.typescriptlang.org/docs/handbook/generics.html)。

为了限制 classDecorator 可以使用的类型类,您在 extends: 之后指定它extends {new(...args:any[]):{}。您基本上是说您的类需要通过 this ( new...)在其定义中使用构造函数。

据我所知,它没有被设置为默认模板,因为装饰器模式没有在打字稿定义以及许多其他现有模式中明确定义。