HomeBrew HomeBrew - 2 months ago 14
TypeScript Question

Typescript errors when setting declaration to TRUE

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.

Answer

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()
    });
}
Comments