Consistent Type Imports and Exports: Why and How
· 6 min read
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.
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!