'Angular in Typescript: how to pass generic Type to function

Using Typescript to write an Angular 5 unit tests, I have a function that will query the DOM and return an instance of the MyComponent class if found:

function getMyComponent(hostFixture: ComponentFixture<any>): MyComponent {
  const debugElement = hostFixture.debugElement.query(By.directive(MyComponent));

  return (debugElement && debugElement.componentInstance) || null;
}

This works flawlessly. Now I'd like to generalize the function so that it could query any Type on demand. I figured this could be done with generic typesThe function would be called like so:

const instance: MyComponent = getDirective<MyComponent>(fixture);

I can't get it working though; Here is the broken function:

function getDirective<T>(hostFixture: ComponentFixture<any>): T {
  const debugElement = hostFixture.debugElement.query(By.directive(T));

  return (debugElement && debugElement.componentInstance) || null;
}

The first line within the function throws the error:

TS2693: 'T' only refers to a type, but is being used as a value here

What is the right syntax here? The Angular function I'm calling -- By.directive() -- takes an argument of type Type<any>, and is documented here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source