import
and export
statements are core features of the JavaScript language.
They were added as part of the ECMAScript Modules (ESM) specification, and now are generally available in most mainstream JavaScript environments, including all evergreen browsers and Node.js.
When writing TypeScript code with ESM, it can sometimes be desirable to import or export a type only in the type system. Code may wish to refer to a type, but not actually import or export a corresponding value.
For that purpose, TypeScript 3.8 added type-only imports and exports to the TypeScript language:
import type { SomeThing } from './some-module.js';
export type { SomeThing };
The key difference with export type
and import type
is that they do not represent runtime code.
Attempting to use a value imported as only a type in runtime code will cause a TypeScript error:
import type { SomeThing } from './some-module.js';
new SomeThing();
// ~~~~~~~~~
// 'SomeThing' cannot be used as a value
// because it was imported using 'import type'.
TypeScript 4.5 also added inline type qualifiers, which allow for indicating that only some specifiers in a statement should be type-system-only:
import { type SomeType, SomeValue } from './some-module.js';
Type-only imports and exports are not emitted as runtime code when code is transpiled to JavaScript. This brings up two questions:
- Why would you want to use these type-only imports and exports?
- How can you enforce a project use them whenever necessary?
Let's Dig In!