I have a function that needs to accept a generic argument type which is constrained to implement a specific interface. I achieved this by defining the interface, an abstract stub class implementing the interface, and using the typeof
operator to reference the abstract stub class.
Below is a code sample demonstrating the issue and solution:
interface Interface {
get FooVal(): any;
}
abstract class StubClass implements Interface {
abstract get FooVal(): any;
}
function Foo<T extends typeof StubClass>( bar: T ) { }
function Bar<T extends Interface>( bar: T ) { }
class UserClass implements Interface {
get FooVal() { return null; }
}
Foo( UserClass ); // No Errors/Warnings
Bar( UserClass ); // Argument of type 'typeof UserClass' is not assignable to parameter of type 'Interface'.
Is there a way to achieve this without defining the abstract stub class?