Picci
Picci

Reputation: 17762

Typescript error: "Return type of exported function has or is using name <n> from external module <M> but cannot be named"

With Typescript 2.6.2, I have developed a function which returns an Observable. This function has been developed within a module that I have published as package named my-package.

The function is defined in the file my-function.ts as such

import { Observable } from 'rxjs/Observable';

export function myFunction() {
    return Observable.from([1,2,3]));
}

The module has its index.ts as such

import {myFunction} from './my-function';

export {myFunction};

Now I want to use my-function in a different project. Therefore I import my-package and then write a new function, newFunction, that uses my-function in a file which looks like

import {myFunction} from 'my-function';

export function newFunction() {
    return myFunction();
}

If I do so, when I try to compile this last file I get an error whose text is

Return type of exported function has or is using name 'Observable' from external module "~/node_modules/rxjs/Observable" but cannot be named.

In order to fix this problem, I have to change the code of newFunction as such

 import { Observable } from 'rxjs/Observable';
 import {myFunction} from 'my-function';

 export function newFunction(): Observable<any> {
     return myFunction();
 }

Is there a way to avoid the compiler problem without having to declare explicitly the return type of newFunction?

Upvotes: 1

Views: 3063

Answers (1)

artem
artem

Reputation: 51729

That error message specifically mentions "name Observable", which is not within the scope of the module where newFunction is defined, which prevents compiler from generating type declaration file for that module.

To fix it, you only need to import that name - Observable - and nothing more. Just add this line to newFunction module:

import { Observable } from 'rxjs/Observable';

That's enough to enable the compiler to spell out inferred return type for newFunction in generated .d.ts file, you don't have to declare that return type explicitly.

Upvotes: 4

Related Questions