When using Typescript for Angular 5 unit tests, I have created a function that can query the DOM and return an instance of the MyComponent
class if it exists:
function getMyComponent(hostFixture: ComponentFixture<any>): MyComponent {
const debugElement = hostFixture.debugElement.query(By.directive(MyComponent));
return (debugElement && debugElement.componentInstance) || null;
}
This function is working perfectly. Now, I want to make it more versatile so that it can query any Type as needed. I thought this could be achieved with generic types. The updated function call would look like this:
const instance: MyComponent = getDirective<MyComponent>(fixture);
However, I am facing issues getting this new version of the function to work correctly. Here is the problematic part:
function getDirective<T>(hostFixture: ComponentFixture<any>): T {
const debugElement = hostFixture.debugElement.query(By.directive(T));
return (debugElement && debugElement.componentInstance) || null;
}
The error message that appears says:
TS2693: 'T' only refers to a type, but is being used as a value here
I'm struggling to figure out the correct syntax in this scenario. The function I am using from Angular -- By.directive()
-- expects a parameter of type Type<any>
, which is documented here