假设我有一个AbstractPageComponent
类,该类具有一个setData
方法:
abstract class AbstractPageComponent<TPageData extends object> {
setData(data: TPageData) {
Object.assign(this, data);
}
}
所以问题是如何告诉Typescript AbstractPageComponent
类实现TPageData
?这不起作用:
abstract class AbstractPageComponent<TPageData extends object> implements TPageData {...}
当前使用此抽象类不是很方便:
interface SomePageData {
foo: FooItem;
bar: BarItem;
}
export class SomePageComponent
extends AbstractPageComponent<SomePageData>
implements SomePageData {
foo: FooItem;
bar: BarItem;
}
它要求最终用户编写implements SomePageData
并复制其所有字段。我想实现的是这样:
interface SomePageData {
foo: FooItem;
bar: BarItem;
}
export class SomePageComponent
extends AbstractPageComponent<SomePageData> {
someMethod() {
// this.foo and this.bar are available
}
}
有可能吗?
答案 0 :(得分:0)
请尝试以下操作:
export class AbstractPageComponent<T> implements T {
}
在另一个文件中:
interface SomePageData{
foo: FooItem;
bar: BarItem;
}
export class SomePageComponent extends AbstractPageComponent<SomePageData> {
}
答案 1 :(得分:0)
No, it's not possible. Typescript treats class type quite differently from other type that's created using type
or interface
keyword.
The code you're currently using is pretty much the optimal solution IMHO.