Here is the Typescript code snippet in question:
interface IBase
{
f():void;
}
class CBase<T extends IBase> implements T
{
f():void
{
//logic here
}
}
Encountered error message:
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'.
The compiler aims to prevent a certain condition. How can this obstacle be overcome? The intention is to have multiple interfaces (all derived from a common base) along with corresponding classes that implement them, while sharing a central set of functionality. For example:
interface IFoo extends IBase{}
interface IBar extends IBase{}
class CFoo extends CBase<IFoo>{}
class CBar extends CBase<IBar>{}
All classes share the implementation of f()
defined in CBase
, however, IFoo
and IBar
are not interchangeable types.
Similar issue discussed here.
While similar object hierarchies work in C++, they face limitations in C# due to the inability to derive from generic parameters.
The objectives of the design are:
- keep specialized class/interface pairs (
IFoo
/CFoo
) as concise as possible - avoiding explicit method declarations within them - ensure a one-to-one relationship between specialized classes and interfaces (e.g., allowing mapping
IFoo
only toCFoo
and no other class)