TypeScript Modules in Depth
A module can import a type without importing any runtime code. The import type form marks that split, and a re-export lets one file pass an API onward.
The store.ts file
The store file holds a product type, a type alias, and one function. The file exports all three names.
export interface Product {
id: number;
name: string;
}
export type ProductId = number;
export function formatProduct(product: Product): string {
return product.id + ": " + product.name;
}Splitting type and value imports
The type names arrive through import type, and the function arrives through a value import. Only the function exists at runtime.
import type { Product, ProductId } from './store';
import { formatProduct } from './store';
const itemId: ProductId = 1;
const item: Product = { id: itemId, name: 'Notebook' };
console.log(formatProduct(item));The api.ts file
The api file defines nothing itself. It re-exports the function as a value and the types with export type.
export { formatProduct } from './store';
export type { Product, ProductId } from './store';Importing through a re-export
The caller imports from the api file and never names the store file. The chain still ends at the same function.
import type { Product } from './api';
import { formatProduct } from './api';
const item: Product = { id: 2, name: 'Pen' };
console.log(formatProduct(item));Example
import type { Product } from './store';
import { formatProduct } from './api';
const items: Product[] = [
{ id: 1, name: 'Notebook' },
{ id: 2, name: 'Pen' },
];
for (const item of items) {
console.log(formatProduct(item));
}Key points
- The import type form imports only a type, and the import is erased when the code compiles.
- A value import brings in runtime code such as a function, and it stays in the compiled output.
- The export type form re-exports a type from a module without creating a runtime value.
- A re-export chain lets callers import from one entry file while the definitions stay in their home file.
- Splitting type and value imports states which names the program needs at runtime.
In this example, the code imports the Product type from the store file and the formatProduct function through the api re-export, then prints both products in order.
Note
A type imported with a plain import and used only as a type is also erased, but import type makes the intent explicit.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does import type guarantee about the imported name?