Here is live example (抱歉,必须使用 url 缩短器,链接字符会破坏标记) TypeScript 版本 1.6.2
我的 angular2 应用程序有两项服务。我们将它们命名为 ServiceA 和 ServiceB。它们中的每一个都具有相似的数据结构,因此我决定使用 extends
来避免重复编写相同的代码。提供数据结构的类称为 Pages,如下所示:
class Pages {
public pages = [];
private active: number = 0;
get current() {
return this.pages[this.active];
}
constructor(private page, public name: string) { }
changeActive(page: number): void {
this.active = page;
}
addPage(): void {
this.pages.push(
new this.page(this.name + (this.pages.length + 1))
);
}
}
pages
数组将包含每个服务唯一的类实例。以下是 ServiceA 的示例:
// ServiceA.pages will be filled with instanced of this class.
// ServiceB.pages will use different class but the constructor
// will be simmilar(will take only one argument name: string)
class PageA {
public uniquePropertyA: string = 'Hello World!';
constructor(public name: string) { }
// unique methods of PageA
}
服务看起来非常相似。这里是 ServiceA 的预览:
class ServiceA extends Pages {
constructor() {
super(PageA, 'ServiceA #');
}
}
// demo
var sA = new ServiceA();
sA.addPage();
sA.current. // Hey there is no auto complete!
这个示例工作正常,但是我没有自动完成每个页面,因为它的类型是any
。我试图使用“泛型”来使其工作,遗憾的是没有成功,但 here it is 。基本上我想知道我传递给 Pages
类的构造函数,这样我就可以获得正确的类型。
希望你们能帮我解决这个问题。
最佳答案
您无法访问泛型类中的页面属性,因为您正在使用泛型类型 T,因此编译器此时没有关于您稍后将如何使用该类的信息。
如果您需要执行绑定(bind)到特定类型的操作,则不能在泛型类中执行此操作。
您可以做的是,在您的类上使用通用约束。例如其中 BasePage 是一个接口(interface),例如
interface BasePage {
name: string;
}
类将是这样的:
class Pages<T extends BasePage>
您可以像这样在 PageA 和 PageB 中实现您的接口(interface):
PageA implements BasePage
然后您就可以访问泛型类中的 name 属性。
更新的示例:http://goo.gl/Pg85Wx
关于javascript - 使用泛型将类作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973790/