【发布时间】:2018-07-02 19:52:00
【问题描述】:
使用 Typescript 编写 Angular 5 单元测试,我有一个函数可以查询 DOM 并在找到时返回 MyComponent 类的实例:
function getMyComponent(hostFixture: ComponentFixture<any>): MyComponent {
const debugElement = hostFixture.debugElement.query(By.directive(MyComponent));
return (debugElement && debugElement.componentInstance) || null;
}
这完美无缺。现在我想概括一下这个函数,以便它可以按需查询任何类型。我想这可以用泛型类型来完成。函数会这样调用:
const instance: MyComponent = getDirective<MyComponent>(fixture);
我无法让它工作;这是损坏的功能:
function getDirective<T>(hostFixture: ComponentFixture<any>): T {
const debugElement = hostFixture.debugElement.query(By.directive(T));
return (debugElement && debugElement.componentInstance) || null;
}
函数内的第一行抛出错误:
TS2693:'T' 仅指一种类型,但在此处用作值
这里的正确语法是什么?我正在调用的 Angular 函数 -- By.directive() -- 接受 Type<any> 类型的参数,并且是 documented here
【问题讨论】:
-
Angular 的
Type<T>是一个糟糕的 API。您是许多被其坦率不负责任的命名误导的人之一。Type<T>真正的意思是Constructable<T>。它是你可以用new调用的值的类型 -
@AluanHaddad 那么这是否意味着我的通用函数需要接受这个 Constructable 作为参数才能工作?我无法从泛型类型
T中提取 Constructable? -
不,你可能不会。 TypeScript 类型是纯粹的设计时构造。请参阅我的答案,了解如何使其发挥作用。
标签: angular typescript generics