Type-only imports and exports by andrewbranch · Pull Request #35200 · microsoft/TypeScript (original) (raw)
TL;DR:
import type { A } from './mod'
,export type { A } from './mod'
- Add flag to stop eliding import declarations from emit
To do:
- parsing
- checking: default import
- checking: named imports
- checking: named exports
- checking: namespace import
- update isolatedModules error message
- test with enums
- isolatedModules code fix
- auto imports behavior
- compiler flag, emit behavior
- checker API (
getTypeAtLocation
) - grammar error for mixing default and named bindings
- code fix for splitting a default + named bindings into two import declarations
- error for usage in JS
- check/improve parsing diagnostics for common mistakes
- test more quick info, completions, rename, etc.
- TextMate grammar
- auto-import/codefix for name in value space that’s already type-only imported?
- code fix for
--importsNotUsedAsValue=error
error
Background
TypeScript elides import declarations from emit where, in the source, an import clause exists but all imports are used only in a type position [playground]. This sometimes creates confusion and frustration for users who write side-effects into their modules, as the side effects won’t be run if other modules import only types from the side-effect-containing module (#9191).
At the same time, users who transpile their code file by file (as in Babel, ts-loader in transpileOnly
mode) sometimes have the opposite problem, where a re-export of a type should be elided, but the compiler can’t tell that the re-export is only a type during single-file transpilation (#34750, TypeStrong/ts-loader#751) [playground].
Prior art
In early 2015, Flow introduced type-only imports which would not be emitted to JS. (Their default behavior, in contrast to TypeScript’s, was never to elide imports, so type-only imports for them were intended to help users cut down on bundle size by removing unused imports at runtime.)
Two months later, #2812 proposed a similar syntax and similar emit behavior for TypeScript: the compiler would stop eliding import declarations from emit unless those imports were explicitly marked as type-only. This would give users who needed their imports preserved for side effects exactly what they wanted, and also give single-file transpilation users a syntactic hint to indicate that a re-export was type-only and could be elided: export type { T } from './mod'
would re-export the type T
, but have no effect on the JavaScript emit.
#2812 was ultimately declined in favor of introducing the --isolatedModules
flag, under which re-exporting a type is an error, allowing single-file transpilation users to catch ambiguities at compile time and write them a different way.
Since then
Over the last four years after #2812 was declined, TypeScript users wanting side effects have been consistently confused and/or frustrated. They have workarounds (read #9191 in full for tons of background and discussion), but they’re unappealing to most people.
For single-file transpilation users, though, two recent events have made their lives harder:
- In TypeScript 3.7, we sort of took away
--isolatedModules
users’ best workaround for reexporting a type in Prevent collision of imported type with exported declarations in current module #31231. Previously, you could replaceexport { JustAType } from './a'
with
import { JustAType } from './a';
export type JustAType = JustAType;
But as of TypeScript 3.7, we disallow the name collision of the locally declaredJustAType
with the imported nameJustAType
. - If a Webpack user was left with an erroneous
export { JustAType } from './a'
in their output JavaScript, Webpack 4 would warn, but compilation would succeed. Many users simply ignored this warning (or even filtered it out of Webpack’s output). But in Webpack 5 beta, @sokra has expressed some desire to make these warnings errors.
Proposal
- Add type-only imports and exports similar to Implicit module import/export elision #2812 and Flow
Change the default emit behavior of the compiler to stop eliding regular imports even if the imported names are only used in type positions- Always elide imports and re-exports explicitly marked as type-only
Add a (temporary?) compiler flag that restores the current behavior of eliding imports that are used only for types to help users with back-compat- Updated: Leave the default emit as-is, adding the flag
--importsNotUsedAsValue <"remove" | "preserve" | "error">
to control the behaviorremove
is default; maintains today’s behaviorpreserve
keeps imports used only for types in the emit as a side-effect importerror
acts aspreserve
but also adds an error whenever animport
could be written as animport type
Syntax
Supported forms are:
import type T from './mod'; import type { A, B } from './mod'; import type * as Types from './mod';
export type { T }; export type { T } from './mod';
Possible additions but I think not terribly important:
export type * from './mod'; export type * as Types from './mod'; // pending #4813
We notably do not plan to support at this time:
type
modifier on import/export specifiers:import { type A } from './mod'
,export { A, type B }
- Mixing a type-only default import with named or namespace imports:
import type T, { A } from './mod'
,import type T, * as ns from './mod'
The forms in the former bullet will be syntax errors; the forms in the latter will be grammar errors. We want to start with productions that can be read unambiguously, and it’s not immediately clear (especially in the absence of Flow’s implementation), what the semantics of import type A, { B } from './mod'
should be. Does type
apply only to the default import A
, or to the whole import clause? We prefer no one need wonder.
Type semantics
Any symbol with a type side may be imported or exported as type-only. If that symbol has no value side (i.e., is only a type), name resolution for that symbol is unaffected. If the symbol does have a value side, name resolution for that symbol will see only the type side. The typical example is a class:
// @Filename: /a.ts export default class A {}
// @Filename: /b.ts import type A from './a'; new A(); // ^ 'A' only refers to a type, but is being used as a value here.
function f(obj: A) {} // ok
If the symbol is a namespace, resolution will see a mirror of that namespace recursively filtered down to just its types and namespaces:
// @Filename: /ns.ts namespace ns { export type Type = string; export class Class {} export const Value = ""; export namespace nested { export class NestedClass {} } } export default ns;
// @Filename: /index.ts import type ns from './ns'; const x = ns.Value; // ^^ Cannot use namespace 'ns' as a value.
let c: ns.nested.NestedClass;
Emit
Updated: When the importsNotUsedAsValue
flag is set to 'preserve', type-only import declarations will be elided. Regular imports where all imports are unused or used only for types will not be elided (only the import clause will be elided):
// @importsNotUsedAsValue: preserve
// @Filename: /a.ts import { T } from './mod'; let x: T;
// @Filename: /a.js import "./mod"; let x;
Back-compat flag
There’s a new flag removeUnusedImports
. Its name is not perfect because it really means “remove imports that have imported names that never get used in a value position.” Open to suggestions.
Updated: this PR is backward-compatible by default.
Auto-imports behavior
- Symbols without a value side will be imported as type-only if there’s not already a regular import from the containing module. If there’s an existing import from the containing module, it will be added to that import (as happens today).
- There will be a configuration option to disable type-only auto imports entirely (since some people use VS Code’s TypeScript version for editor services but compile with an older version).
I’m not yet confident what other changes, if any, will the right move, but the main scenarios to consider are:
- User auto imports a class, enum, or namespace in a type position. Should we do a type-only import?
- User has a type-only import of a class, enum, or namespace, then later tries to use the same symbol in a value position. Do we convert the type-only import to a regular import? (Is that even possible with a completions code action?)
Successor of #2812
Closes #9191
Closes #34750
Would close if they were still open:
- Explicit keyword for type-only import #20433
- importing type declaration files #16472
- Request: compiler option to disable elision of "unused" imports #18586
- Typescript should not be doing code removal for non TS code #30525
- ES Module imports discarded when they include a type and a side-effect #28285