5

I'm trying to create typescript definitions for a Angular 2 project I'm working on so that it can be an exportable library.

I have several services setup that return http requests to components all quite similar to the following:

public create(user:User) {
  return this.http.post(this._apiUrls.create,
    JSON.stringify(user), {
      headers: this.apiConfig.getApiHeaders()
    });
}

Which I then call from a component something like this:

Session.create(user).subscribe((res:Response) => {
  this.user = res.json().user
}); 

This all works fine until I turn 'declaration' to true in the tsconfig file so that I can create typescript definition files. I start to get the following errors for several of my services:

error TS4053: Return type of public method from exported class has or is using name 'Observable' from external module "node_modules/rxjs/Observable" but cannot be named.

I mostly understand the problem but I don't know a solution. If I import Observable into the service then the typescript linter will throw errors because technically it's not being used in that file.

Coming from Angular 1 this was a similar paradigm we took in all ours apps to break our code apart but maybe I need to change the approach in Angular 2? I've looked at lots of other Angular 2 examples and they have all done it in a similar way also.

1 Answer 1

5

As of today, the compiler won't automatically import types for you in a declaration file.

The best workaround for now is to manually disable your lint rules for the import, or to import the type and use an explicit type annotation so that the linter marks it as a usage.

In other words

// Explicit import of 'Observable' so that '.d.ts' files
// can be generated correctly.
import { Observable } from "node_modules/rxjs/Observable";

// Explicit use of 'Observable' to satisfy your linter.
public create(user: User): Observable {
  return this.http.post(this._apiUrls.create,
     JSON.stringify(user), {
       headers: this.apiConfig.getApiHeaders()
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

Some examples would have been nice
I didn't understand your solution. Can you explain me more clearly on what to do?
The author said that if they import Observable explicitly (i.e. import { Observable } from "node_modules/rxjs/Observable"), then that will fix the error. So that's the solution. The thing that made that solution problematic is that their linter considered Observable to be unused. The solution for that was to actually use Observable as the return type (i.e. public create(user: User): Observable). I've updated my answer to clarify.

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.