TypeScript: Spurious "Identifier 'angular' must be imported from a module" error

TypeScript Version:

2.0.2

Code

https://github.com/jonrimmer/typescript-bug

npm install
./node_modules/.bin/tsc bug.ts

Expected behavior:

It should compile without problems.

Actual behavior:

It gives the following error:

node_modules/angular-ui-router/commonjs/ng1/services.d.ts(2,27): error TS2686: Identifier 'angular' must be imported from a module

This is despite the fact that the @type/angular definitions includes a global angular var declaration.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 10
  • Comments: 17 (6 by maintainers)

Commits related to this issue

Most upvoted comments

I have to be honest, while I basically understand the reasoning, the choice of making this work globally only if there are no imports or exports in the file seems completely arbitrary and comes across as a bad choice for both usability and backwards compatibility. At the very least this should have been configurable or provide an easy way to work around it.

I am now spending a great deal of what feels like unnecessary time on this while trying to move a fairly large project towards Angular 2 and Typescript 2 and this is creating unnecessary friction. If every update to the Typescript project is going to just add a new bar to jump over like this I’m really going to need to reconsider using it.

So far I’ve found this to be a common pattern with using Typescript. Many inexplicable behaviours and decisions each of which is hard to track down or find documentation around.

this is an issue in angular-ui-router declaration file. The compiler tries to ensure that a UMD module is used consistently, either as a module or as a global.

File: node_modules\angular-ui-router\commonjs\ng1\services.d.ts

should be:

import * as angular from "angular";
import IInjectorService = angular.auto.IInjectorService;

Thanks @RyanCavanaugh it is probably also worth noting that calling import * as angular from 'angular' in each file does not work properly with Webpack as it will try to load angular multiple times.

The only solution is to add declare var angular at the top of each problematic file, which is far less than ideal.

By the way, the title problem was solved by me in that way:

// _shim.d.ts
import * as __angular from "angular";

declare global {
    const angular: typeof __angular;
}

@Gugic Apparently my globals file can’t declare a globals namespace because its not ambient though it ends in .d.ts due to something else silently triggering it not being ambient or something

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.at line 64 col 9

There are so many pitfalls in ts modules

My globals.d.ts now consists entirely of

declare global { }

and I still get that error