Modules & Declaration Files
import/export with types, type-only imports, .d.ts files, and @types packages
Skills taught: ts.named-exports, ts.default-exports, ts.type-imports, ts.declaration-files, ts.types-packages
Exporting and importing types
// types.ts — exporting types
export interface User {
id: number;
name: string;
email: string;
}
export type Status = 'active' | 'inactive' | 'pending';
export type UserId = number;
// exporting a class (type AND value)
export class UserError extends Error {
constructor(public code: number, message: string) {
super(message);
}
}
// service.ts — importing types and values
import { User, Status, UserId, UserError } from './types';
// OR — import only the type, erased at compile time:
import type { User, Status, UserId } from './types';
// type-only import: never generates a require() in JS output
// Use for interfaces, type aliases, and other compile-time-only items
const users: User[] = [
{ id: 1, name: 'Alice', email: 'alice@ex.com' },
{ id: 2, name: 'Bob', email: 'bob@ex.com' },
];
function findUser(id: UserId): User | undefined {
return users.find(u => u.id === id);
}
function setStatus(user: User, status: Status): User {
console.log(`Setting ${user.name} to ${status}`);
return { ...user };
}
// Default export
export default { findUser, setStatus };
// .d.ts file — pure type declarations (no JS emitted)
// Used by library authors and @types packages
// Describes a JavaScript library that has no TypeScript source
declare module 'my-js-lib' {
export function compute(input: number): number;
export const VERSION: string;
export interface Config {
timeout?: number;
retries?: number;
}
export default function(config?: Config): void;
}
// Global augmentation — add to existing globals
declare global {
interface Window {
analytics: {
track(event: string, data?: Record<string, unknown>): void;
};
}
}
export {};
Frequently Asked Questions
When do I need @types packages?
When a JavaScript library doesn't ship TypeScript types itself. npm install -D @types/node adds types for Node.js built-ins. @types/react adds React types. Modern libraries (zod, prisma, tanstack query) bundle their own types and don't need a separate @types package. Check the library's README or look for a types or typings field in its package.json.