6

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 Answers 2

5

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>.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.