Search code examples
typescriptmultiple-inheritancetypescript1.5

Typescript - Is there a way to do this without multiple inheritence


Typescript does not allow multiple inheritance. If it did, the below works. Without it, how can I do this?

I have a class CellProps that holds the vars for formatting a cell. It has a ton of members but for this example, assume it's:

export class CellProps 
{
public width: number;
}

And there's a TableProps that has all the cell formatting, and more. So for this example it's:

export class TableProps
{
public autoFit : boolean;
}

The above are objects in both styles and in Table & Cell objects. Here's where it get's complicated, in the styles all we have are the values. But in the Table & Cell objects, if the value is defined in that object, that's the value. But if the value is undefined/null, then we have to go look in that object's style to see if it's set there. (This is modeling Microsoft Word.)

To do this, the styles have a TableProperties (and in some cases a CellProps). But in the Table & Cell classes, they have instances of:

export class TablePropValues extends TableProps
{
// ...
public isAutoFit() : boolean
{
// return this.autoFit if defined, otherwise check the style.
}
}
export class CellPropsValues extends CellProps 
{
public getWidth() : number
{
// return this.width if defined, otherwise check the style.
}
}

Here's the problem. What I really need is:

export class TablePropValues extends TableProps, CellPropsValues 
{
}

Because in TablePropValues I need both getWidth() and autoFit. It's not just the vars I need from both, it's the methods and their implementations.

And yes I can use just TablePropValues and have no TableProps and it all works. But then I lose the compile time checking that will make sure that when using the style based object I don't call the getter - and that's incredibly useful.

Both TablePropValues and CellPropsValues add a single private (and no public) var that has the same name and class. This is used to walk up to the style object if needed. So if Typescript had a #include, that would solve this problem too.

Any way to do this? The best I've come up with is say it implements an interface for each and in the constructor copy the method implementations into the prototype. But that strikes me as something fragile (could not work in some javascript implementations).

Or copy the code across and have a note there that any changes must be made to both classes. But duplicate code is asking for duplicate bugs.


Solution

  • Any way to do this? The best I've come up with is say it implements an interface for each and in the constructor copy the method implementations into the prototype

    Don't copy the stuff into the prototype and use the mixins pattern instead : http://www.typescriptlang.org/docs/handbook/mixins.html