Microsoft/TypeScript

Give better error message when trying to import something declared as a global

Open

#46.687 aberto em 4 de nov. de 2021

Ver no GitHub
 (0 comments) (3 reactions) (0 assignees)TypeScript (6.726 forks)batch import
Domain: Error MessagesEffort: ModerateExperience EnhancementHelp WantedSuggestion

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

Suggestion

🔍 Search Terms

import global error message

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

If you write import Foo from "foo" and "foo" resolves to a declaration file that is not a module but declares a global named Foo, we should give a better error message suggesting how to resolve the incorrect import. The current one is

File '{0}' is not a module.

Globals are weird so we can’t always tell what the user was trying to do, but I think we can get it right a good chunk of the time by checking whether this file was already included in the program by some other inclusion reason besides this erroneous import—if so, suggest simply removing the import declaration and referencing Foo as a global. If not, suggest dropping the import clause: import Foo from "foo"import "foo".

Note I think this only applies when every name specified by the import declaration exactly matches a global declared in the resolved file (and the file is not also a module that just happens to declare some globals via global augmentation).

📃 Motivating Example

@soffes hit this when trying to import from shaka-player and vaguely understood what the error message was saying, but not how to resolve it. It was particularly confusing because the file wasn’t already in his program, so upon writing the bad import, everything seemed to work except TypeScript complained at the import declaration site. This looks like the import is actually working but TypeScript is complaining about it for some inscrutable reason, when in fact, the shaka name is resolving only because the bad import successfully gets the global declaration into the program.

Guia do colaborador