0

When trying to assign a generic type to Type<any>, i cannot get the type constraint correct when i know the type is an angular component.

However directly assigning a component type works.

This works

private routeComponent: Type<any>;
public component<TComponent>(): RouteBuilder {
    this.routeComponent = HomeComponent;
    return this;
}

This doesnt.

private routeComponent: Type<any>;
public component<TComponent>(): RouteBuilder {
    this.routeComponent = TComponent;
    return this;
}

It fails with

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

How can i make it so my component method accepts only a Component, or if cant do that at least be able to assign the generic type to the Type<any> the same as i can if i do it direct.

1 Answer 1

1

Generics are implemented in Typescript using type erasure, so at runtime TComponent will not available. You can pass the class as an argument to the function instead :

public component<TComponent>(type: Type<TComponent>): RouteBuilder {
    this.routeComponent = type;
    return this;
}
component(HomeComponent);
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! just what i was looking for, thanks very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.