[英]TypeScript Class Generic Parameter Constraints
I'm attempting to declare a TypeScript class with a constrained generic parameter. 我试图用受约束的通用参数声明TypeScript类。 In C#, the following would compile:
在C#中,将编译以下内容:
public class NewClass<T> where T: BaseClass {
}
What is the TypeScript equivalent? 什么是TypeScript等效项?
You're looking for the extends
keyword. 您正在寻找
extends
关键字。 You can use it right after the generic parameter to constrain it to be a subtype of the specified type. 您可以在通用参数之后立即使用它,以将其约束为指定类型的子类型。
So the equivalent for your example would be: 因此,您的示例等效于:
class NewClass<T extends BaseClass> {
// Things...
}
You can read more about generic constraints in the documentation here . 您可以在此处的文档中了解有关通用约束的更多信息。
For both classes and interfaces as base, you have to constrain T
like this: 对于作为基类的类和接口,必须像这样约束
T
:
export class NewClass<T extends BaseClass> {
}
While you derive classes from interfaces with implements
, the same is not true for generic constraints, making this code possible: 当您从具有
implements
接口派生类时,对于通用约束而言并非如此,因此使此代码成为可能:
export class NewClass<T extends BaseInterface> implements BaseInterface {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.