Jer*_*ter 5 typescript typescript-generics angular2-testing angular angular-test
Angular 可以按类型查询子组件,在测试中使用它,如下所示:
fixture.debugElement.query( By.directive( ComponentType ) );
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个为我执行此操作的函数:
import { ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Type } from '@angular/core';
export function findSubComponent<T>( fixture: ComponentFixture<any>, componentType: T & Type<any> ): T {
const subComponentDebugElement = fixture.debugElement.query( By.directive( componentType ) );
return subComponentDebugElement.componentInstance;
}
Run Code Online (Sandbox Code Playgroud)
现在问题来了。我的函数当前返回typeof ComponentType而不是实际的对象ComponentType,因此我无法访问它的属性。
这里的 TypesubComponentDebugElement.componentInstance是 any,所以我可以在返回 Type 参数中声明类型(function (): T)
typeof ComponentInstance我怎样才能将本例中代表的 T 变成ComponentInstance?InstanceType<T>正如@jcalzInstanceType<T>所建议的,解决方案是这样使用:
type AbstractClassType = abstract new ( ...args: any ) => any;
export function querySubComponent<T extends AbstractClassType>(...): InstanceType<T> {
...
}
Run Code Online (Sandbox Code Playgroud)
AbstractClassTypeasabstract new ( ...args: any ) => any请注意,您现有的类型定义可能不需要 AbstractClassType,但显然泛型InstanceType<>需要使用带有构造函数的类型,否则我会收到以下 TS-Error:Type 'T' does not satisfy the constraint 'abstract new (...args: any) => any'.
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |