The following Typescript:
interface IBase
{
f():void;
}
class CBase<T extends IBase> implements T
{
f():void
{
//logic here
}
}
is giving me an error:
Class 'CBase' incorrectly implements interface 'T'. 'CBase' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'IBase'.
What condition exactly is the compiler trying to prevent, and how do I work around that? What I ultimately want is to have several interfaces (with a common base) with corresponding classes that implement them, but with one underlying set of functionality. Something like this:
interface IFoo extends IBase{}
interface IBar extends IBase{}
class CFoo extends CBase<IFoo>{}
class CBar extends CBase<IBar>{}
and they all share the same implementation of f()
, the one in CBase
, but in the way that IFoo
and IBar
are not compatible types.
Similar issue here?
For the record, this object hierarchy works in C++ (modulo lack of template constraints), but doesn't in C#, since you can't derive from generic parameters in C#.
The design goals are:
- specialized class/interface pairs (
IFoo
/CFoo
) are as minimal as possible - no methods spelled out explicitly in those - specialized classes and interfaces are in one to one correspondence (so that
IFoo
can be mapped toCFoo
and nothing else)