I'm attempting to declare a TypeScript class with a constrained generic parameter. In C#, the following would compile:
public class NewClass<T> where T: BaseClass {
}
What is the TypeScript equivalent?
I'm attempting to declare a TypeScript class with a constrained generic parameter. In C#, the following would compile:
public class NewClass<T> where T: BaseClass {
}
What is the TypeScript equivalent?
You're looking for the extends
keyword. 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:
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:
export class NewClass<T extends BaseInterface> implements BaseInterface {
}