Typescript:有没有一种说法可以说该类实现了其泛型?

时间:2019-04-08 11:29:58

标签: typescript

假设我有一个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
  }
}

有可能吗?

2 个答案:

答案 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.