In Java I could write something like List<MyClass<? extends MyConstraint>> to express "a list of instances of MyClass instanciated with various types for T, all extending MyConstraint".
It's not the same thing as List<MyClass<MyConstraint>>, because A inheriting MyConstraint doesn't make MyClass<A> assignable to MyClass<MyConstraint>
I think typescript should be expressive enough to express that, but I can't find how to do it... Did I miss something here ?
Oh and our project uses the no-explicit-any eslint rule. So it this situation a valid usecase for List<MyClass<any>> ?
CodePudding user response:
The equivilent in Typescript is actually very similar to what you referenced with Java.
type Foo<T extends MyConstraint> = Array<MyClass<T>>;
This would create an array type where the instances of MyClass have their parameterized generic argument constrained to anything that is a sub-type of MyConstraint just as you had done with Java.
This can come in different flavors depending on what you're doing (creating a type, defining a generic class, defining a generic function, etc) but the basic syntax is <T extends SomeConstraint>.
Here's the relevant Typescript docs talking about generic constraints which covers all the details: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints
