TypeScript by Example

Modules

ES module import/export in TypeScript, import type, and barrel re-exports.

TypeScript uses JavaScript ES module syntax and adds import type for imports that exist only for the type checker.

import type is stripped at compile time, so it cannot create an accidental runtime import.

// user.ts
export type UserId = string;
 
export interface User {
  id: UserId;
  name: string;
}
 
export function createUser(name: string): User {
  return { id: crypto.randomUUID(), name };
}
 
// app.ts
import { createUser, type User } from "./user";
 
const user: User = createUser("Ada");

Barrels collect related exports into one entry point while implementation files stay split.

// lib/auth/session.ts
export interface Session {
  token: string;
}
export function parseSession(raw: string): Session {
  return { token: raw };
}
 
// lib/auth/index.ts
export type { Session } from "./session";
export { parseSession } from "./session";
 
// app.ts
import { parseSession } from "@/lib/auth";

In production

Use import type for type-only imports, especially across module boundaries. It keeps emitted JavaScript honest and prevents type references from turning into empty side-effect imports.

Enjoyed this? Get more software craft delivered to your inbox.