打字稿-有没有办法在没有多重继承的情况下做到这一点

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

Typescript 不允许多重继承。如果是这样,下面的工作。没有它,我怎么办?

我有一个 class CellProps,它包含用于格式化单元格的变量。它有很多成员,但对于这个例子,假设它是:

export class CellProps 
{
public width: number;
}

还有一个 TableProps 具有所有单元格格式等等。所以对于这个例子是:

export class TableProps
{
public autoFit : boolean;
}

以上是两种样式和 Table & Cell 对象中的对象。这就是它变得复杂的地方,在我们拥有的所有样式中都是值。但是在 Table & Cell 对象中,如果该值是在该对象中定义的,那就是该值。但如果值为 undefined/null,那么我们必须查看该对象的样式以查看它是否设置在那里。 (这是为 Microsoft Word 建模。)

为此,样式具有 TableProperties(在某些情况下还有 CellProps)。但在 Table & Cell classes 中,它们有以下实例:

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.
}
}

问题来了。我真正需要的是:

export class TablePropValues extends TableProps, CellPropsValues 
{
}

因为在 TablePropValues 中我需要 getWidth() 和 autoFit。这不仅仅是我需要的变量,还有方法和它们的实现。

是的,我可以只使用 TablePropValues 而没有 TableProps 并且一切正常。但是后来我失去了编译时检查,这将确保在使用基于样式的对象时我不会调用 getter - 这非常有用。

TablePropValues 和 CellPropsValues 都添加了一个具有相同名称和 class 的私有(并且没有 public)变量。如果需要,这用于走到样式对象。所以如果 Typescript 有一个#include,那也可以解决这个问题。

有什么办法吗?我想出的最好办法是说它为每个实现一个接口,并在构造函数中将方法实现复制到原型中。但这让我觉得很脆弱(在某些 javascript 实现中无法工作)。

或者将代码复制过来并在其中注明必须对两个 class 进行任何更改。但是重复的代码要求重复的错误。

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

不要将内容复制到 prototype 中,而是使用混合模式:http://www.typescriptlang.org/docs/handbook/mixins.html