Script Valley
Writing Clean Code: Naming, Functions & Structure
Clean Code in Real ProjectsLesson 6.4

How to apply clean code principles in TypeScript specifically

TypeScript types as documentation, interface naming, type alias vs interface, strict mode, discriminated unions, avoiding any

Clean Code in TypeScript: Types as Documentation

TypeScript types as documentation

TypeScript gives you a tool that JavaScript lacks: types are documentation that the compiler enforces. A well-typed function signature is a contract that can't go stale the way comments do.

// Without types — you must read the body to understand the contract
function createInvoice(customer, items, options) { }

// With types — the signature is self-documenting
function createInvoice(
  customer: Customer,
  items: LineItem[],
  options?: InvoiceOptions
): Promise<Invoice> { }

Use interface for objects, type for unions and aliases:

// Interface — for object shapes (supports extension)
interface User {
  id: string;
  email: string;
  role: UserRole;
}

// Type — for unions
type OrderStatus = 'pending' | 'approved' | 'rejected';
type UserId = string; // makes intent clear, prevents accidental misuse

Enable strict mode in tsconfig.json. It catches the majority of type errors that lead to runtime bugs:

{ "compilerOptions": { "strict": true } }

Never use any. Every any is a hole in the type system that defeats the purpose of TypeScript. Use unknown for truly unknown inputs and narrow the type before using it.

// Bad
function parse(input: any) { return input.value; }

// Good
function parse(input: unknown): string {
  if (typeof input === 'object' && input !== null && 'value' in input) {
    return String((input as { value: unknown }).value);
  }
  throw new Error('Invalid input shape');
}

Up next

How to create a team clean code standard document

Sign in to track progress