· Jake Worth

Type-only imports and exports


You might have seen type-importing code like this before:

utils.ts
export type Color = 'blue' | 'gray';
app.tsx
import {Color} from './utils';

As of TypeScript 3.8, you can and should mark this import as type-only:

app.tsx
import type {Color} from './utils';

What’s the difference? Just one keyword, type. This tells the compiler: “Color is a type. Erase this import after transpilation.”

This matters when types and values share an importing line of code with other things:

app.tsx
import {Color, Wrapper, Container} from './utils';

There’s a sneaky problem here: Color is a type, but Wrapper and Container are React components. TypeScript can usually tell which names are types. But tools that transpile a file alone often can’t— so they need an explicit signal about what to keep in the JavaScript output. Let’s give it to them!

app.tsx
import {type Color, Wrapper, Container} from './utils';

With the type keyword in use, the transpiled JavaScript keeps only the runtime imports:

app.js
import {Wrapper, Container} from './utils';
// `Color` was type-only, so it's gone

TypeScript documentation: Type-only imports and export