5

I am trying to create a generic wrapper around TestBed.createComponent, which takes a type argument and creates the component for that type. However, the TestBed.createComponent function takes an argument of type Type<T>. I'm unable to create a Type<T> from the passed in generic T argument.

export function createTestHarness<T>(): TestHarness<T> {
  let component: T;
  let fixture: ComponentFixture<T>;

  fixture = TestBed.createComponent<T>(**PROBLEM AREA**);
  component = fixture.componentInstance;
  fixture.detectChanges();

  return new TestHarness<T>(component, fixture);
}

Is there a way to derive a Type<T> from the type passed in?

2 Answers2

3

One option you have is to use the Type<T> as a parameter to your function:

function createTestHarness<T>(type: Type<T>): TestHarness<T> {
  let component: T;
  let fixture: ComponentFixture<T>;

  fixture = TestBed.createComponent<T>(type);
  component = fixture.componentInstance;
  fixture.detectChanges();

  return new TestHarness<T>(component, fixture);
}

With the following usage:

const harness = createTestHarness(TestComponent);

Which will return a TestHarness<TestComponent>.

Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38
0

Generics only exists at compile time and not at runtime. So you can not derive the type of T.

Get type of generic parameter

sonallux
  • 83
  • 5