0

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 to CFoo and nothing else)
Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281

1 Answers1

0

I got away with the following:

interface IBase
{
    f():void;
}

class CBase implements IBase
{
    f():void
    {
        //Logic here
    }
}

And then the specializations:

interface IFoo extends IBase{}
class CFoo extends CBase implements IFoo{}

So what I have here is a textbook diamond inheritance, but I'm getting away with it because of unavoidably dynamic call dispatch of JavaScript.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281