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.
Whenever TypeScript finds an error, it tries to explain what went wrong in as much detail as possible. Because its type system is structural, this often means providing somewhat lengthy descriptions of where it found a problem.
The error "Could not find declaration file for module" occurs when TypeScript cannot find the type declaration for a module. To solve the error, install the types for the module by running the command from the error message, e.g. npm install -D @types/module-name .
The "Property does not exist on type Object" error occurs when we try to access a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.
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()
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With