Skip to content

Better error message when using a service with a generic parameter #12262

Closed

Description

@graphicsxp

I'm submitting a ... (check one with "x")

[ *] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

When compiling a Ionic2 application for AOT, the ngc compiler gives me this error.

ngc: Error: Error at C:/dev/ecdt-mobile/.tmp/app/app.module.ngfactory.ts:177:20: Generic type 'BaseService<T>' requires 1 type argument(s).

Expected behavior

It should compile. I have created an angular2 repro (without ionic) and it compiles fine. HOWEVER the generated code is underline in my IDE and I believe this is not right:

 __BaseService_76:import46.BaseService;

it should be something like:
__BaseService_76:import46.BaseService<any>;

Minimal reproduction of the problem with instructions

The repro project is here: https://github.com/graphicsxp/angular2

What is the motivation / use case for changing the behavior?

Please tell us about your environment:

Windows, npm

  • Angular version: 2.0.X 2.0
  • Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ] chrome
  • Language: [all | TypeScript X.X | ES6/7 | ES5]
    typescript 2.0
  • Node (for AoT issues): node --version =
    v4.5.0

Activity

  1. alxhub commented on Oct 18, 2016

    @alxhub
    Member

    This sounds like an Ionic issue - please follow up with them. If you can provide a reproduction of the problem using only Angular, feel free to reopen the issue.

  2. simosalmi commented on Oct 18, 2016

    @simosalmi

    hi, I'm getting the same error as @graphicsxp... Actually, @alxhub, I think the repo he posted doesn't reference Ionic, and the error is reproducible. The type argument is absent for generics in the TS code of the ngfactory. That's what is causing the issue.

  3. alxhub commented on Oct 18, 2016

    @alxhub
    Member

    @graphicsxp @simosalmi

    Okay, I looked through the repo posted. The issue is that you are passing BaseService in your providers. BaseService is a generic class, so attempting to provide it is confusing - Angular doesn't know what type argument you meant to use.

    @chuckjaz may have more insight, but I believe we do need to give a better error message in this case.

  4. reopened this on Oct 18, 2016
  5. added
    area: core
    on Oct 18, 2016
  6. graphicsxp commented on Oct 19, 2016

    @graphicsxp
    Author

    @alxhub You are right. Removing BaseService from the list of providers was all I had to do to make it compiles.
    BUT now it crashes at runtime with the following error: No Provider for BaseService

    error_handler.js:47 EXCEPTION: Uncaught (in promise): Error: Error in ./RequestListComponent class RequestListComponent_Host - inline template:0:0 caused by: **No provider for BaseService!**ErrorHandler.handleError @ error_handler.js:47next @ application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74NgZone.triggerError @ ng_zone.js:278onHandleError @ ng_zone.js:257t.handleError @ polyfills.js:3e.runGuarded @ polyfills.js:3r @ polyfills.js:3i @ polyfills.js:3invoke @ polyfills.js:3
    error_handler.js:52 ORIGINAL STACKTRACE:
    

    That 's why I added BaseService to the list of providers... Any idea what I should do ?

  7. BrainCrumbz commented on Oct 19, 2016

    @BrainCrumbz

    Same issue with us. Angular 2, TypeScript 2, Webpack 2 web application (i.e. no Ionic involved). Development build goes fine. Production build with AOT and UglifyJs complains with:

    ERROR in [default] D:/myproj/codegen/src/app/module.ngfactory.ts:191:21
    Generic type 'RestApiService' requires 1 type argument(s).

    (codegen is the output directory for ngc compiled factories).

    Looking in there:

    // ...
    class AppModuleInjector extends import0.NgModuleInjector<import1.AppModule> {
      // ...
      _RestApiService_65:import43.RestApiService;
      //                 ----------------------- this has the squiggly underline

    Original code is:

    // **** app/module.ts
    
    @NgModule({
      imports: [
        SharedModule.forRoot(),
        // ...
    
    // **** shared/module.ts
    
    export class SharedModule {
      static forRoot(): ModuleWithProviders {
        return {
          ngModule: SharedModule,
          providers: [
            RestApiService,
            // ...

    Of course, generic class is used throughout the app as a dependency with different types passed as T.

  8. BrainCrumbz commented on Oct 19, 2016

    @BrainCrumbz

    Some related explanation might come from the final comments in this issue

  9. graphicsxp commented on Oct 19, 2016

    @graphicsxp
    Author

    @BrainCrumbz I had a look at the other issue in your link. That sentence made me jump off my chair:

    There are some technical challenges that must be overcome and some TypeScript features that need to be added for this to be implemented correctly that we currently don't believe adding this support provides enough value to justify the cost of its implementation.

    If generics is not a TypeScript feature that provides value, I don't know what it is then...
    Or maybe I've missed something ?

  10. BrainCrumbz commented on Oct 19, 2016

    @BrainCrumbz

    Tried also by registering typed classes as providers:

    providers: [
      MyProvider, 
      MyOtherProvider,
      RestApiService<MyPayloadA>
      //             ---------- highlighted
    ]

    but that is already highlighted by VS Code, and when building gives an error like:

    Error: Invalid provider for the NgModule 'RelaxingModule' - only instances of Provider and Type are allowed, got: [MyProvider, MyOtherProvider, ?false?]
    at D:\myproj\node_modules@angular\compiler\bundles\compiler.umd.js:14328:25

  11. BrainCrumbz commented on Oct 19, 2016

    @BrainCrumbz

    Tried also declaring specific classes inheriting from generic one, and registering them as providers (here one of those as an example):

    @Injectable()
    export class AuthRestApiService extends RestApiService<MyAuthPayload>{
    }
    
    providers: [
      MyProvider, 
      MyOtherProvider,
      AuthRestApiService
    ]

    No error highlighted in IDE, but when compiling and building:

    ERROR in [default] D:/myproj/codegen/src/app/module.ngfactory.ts:xxx:yyy
    Supplied parameters do not match any signature of call target.

    Looking at factory code:

    this._AuthRestApiService_65 = new import43.AuthRestApiService();
                                  --------------------------------- highlighted

    Error hint in popup says:

    [ts] Supplied parameters do not match any signature of call target.
    constructor AuthRestApiService<import46.AuthPayload>(http: import112.Http): import43.AuthRestApiService

    So it looks like type parameter is ignored when _new_ing the service instance.

  12. chuckjaz commented on Oct 19, 2016

    @chuckjaz
    Contributor

    @graphicsxp I believe you are taking my comment as a general indictment of generics which is not what I intended at all. There are some implementation challenges that make supporting generics in this context very difficult. It is this difficulty that I was trying to convey, not any slight to generics which I find very, very useful.

    I believe the problem with the AuthRestApiService above is that it is inheriting the constructor of RestApiService but the metadata produced for AuthRestApiService declares its constructor doesn't take any parameters. Try repeating the constructor calling the super constructor as a work-around.

    The reason

    providers: [
      MyProvider, 
      MyOtherProvider,
      RestApiService<MyPayloadA>
    ]
    

    doesn't work is because RestApiService<MyPayloadA> is not valid TypeScript because, in this context, RestApiService<MyPayload> is interpreted as RestApiService < MyPayload comparing the two types instead of using MyPayload as a type parameter (which results in false at runtime as you noticed) and the trailing > is reported a a syntax error and is elided in the output.

    The instantiations of a generic types are not reified but are erased following a Java like erasure model. This means that there is no way, at runtime, to distinguish between RestApiService<MyPayloadA> and RestApiService<MyPayloadB> as both translate into a reference to the function RestApiSerivice; so even if this was valid TypeScript we couldn't support it. Creating a subclass that binds the type parameter creates a concrete reified class that can be used as a token for dependency injection.

    DI only supports using concrete reified types as tokens as it must manufacture an instance of the type and the constructor function must be unique to the type. The token cannot be an instantiated generic type because it is ambigious as the type parameters are discarded at runtime and the same constructor function is used for all instantiations.

  13. alxhub commented on Oct 19, 2016

    @alxhub
    Member

    @chuckjaz, is there a way for the compiler/metadata extractor to give a better error message when attempting to use a class with a generic type parameter as an injection token, instead of the current situation where the generated NgFactory code is incorrect and causes the TypeScript error given in the issue's title?

  14. chuckjaz commented on Oct 19, 2016

    @chuckjaz
    Contributor

    @alxhub The static reflector host should be able to figure this out when it is asked to produce the reference to BaseService.

  15. 11 remaining items

  16. chuckjaz commented on Oct 24, 2016

    @chuckjaz
    Contributor

    Your comment on this issue doesn't fall into the bug report or feature request category. This issue tracker is not suitable for support requests, please repost your issue on StackOverflow using tag angular.

    If you are wondering why we don't resolve support issues via the issue tracker, please check out this explanation.

  17. changed the title [-]Generic type 'BaseService<T>' requires 1 type argument(s)[/-] [+]Better error message when using a service with a generic parameter[/+] on Oct 26, 2016
  18. liquidboy commented on Dec 14, 2016

    @liquidboy

    I just hit this issue with our AOT compiled Angular 2 app ... was working perfectly (or what appeared to work perfectly) for the JITed version...

    We are injecting ModalDialogInstance < T > in alot of areas, and T can be whatever "Component" we want to load in the ModalDialogInstance .... Sadly seems like this is causing AOT to fail because as mentioned above the compiler has no idea what to make of T..

    sigh!!!

  19. chuckjaz commented on Dec 14, 2016

    @chuckjaz
    Contributor

    @liquidboy I believe what you are running into is more along the lines of the general principal requested in #12398. What it proposes is to be able to infer generic parameters from the types of the corresponding inputs. The issue uses NgFor as an example but it should work in your case too. What you want, I believe, is for T to be inferred to be the type of the child component used as the dialog instance.

  20. chuckjaz commented on Mar 3, 2017

    @chuckjaz
    Contributor

    Closing as the original issue was fixed by 69e14b5

    Injecting a token with an interface type will be fixed by #14894

    Inferring the type parameter will be deferred to post 4.0. The 4.0 code generation makes this less urgent as the 4.0 generated code will compile without inferring the correct type parameter.

  21. angular-automatic-lock-bot commented on Sep 10, 2019

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  22. locked and limited conversation to collaborators on Sep 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: corefreq1: lowtype: bug/fix

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions