TypeScript Best Practices for Large Codebases

July 27, 2025
#typescript #best practices #clean code

TypeScript brings safety and scalability to JavaScript. But with great power comes great responsibility. Here are some hard-won lessons.


🧼 1. Prefer type over interface

// βœ… Better
type User = {
  id: number;
  name: string;
};

// ❌ Avoid when not extending
interface User {
  id: number;
  name: string;
}

Use type for union, intersection, and readability.


πŸ“ 2. Modularize Types

Avoid a types.ts god file. Instead:

  • Co-locate types with domain logic
  • Export them from index if needed
// user/types.ts
export type User = { id: number; name: string };

// user/index.ts
export * from "./types";

πŸ§ͺ 3. Use Narrow Types

Instead of generic types:

// ❌
function log(level: string) {}

// βœ…
type LogLevel = "info" | "warn" | "error";
function log(level: LogLevel) {}

πŸ“Œ 4. Enforce strict mode

Enable in tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true
  }
}

This avoids silent type issues.


πŸ“š 5. Document Complex Types

/**
 * Represents a GitHub API user payload
 */
type GitHubUser = {
  login: string;
  id: number;
  avatar_url: string;
};

🧠 Final Thoughts

TypeScript doesn’t just catch bugs β€” it also documents intent.


  • ESLint with @typescript-eslint
  • TypeDoc
  • ts-prune (find unused types)
My funny logo

0xws

Welcome !

πŸ‘‹ I’m ws (/vaΙͺs/), a DevSecOps engineer. This site is the place to gather my projects and thoughts on everything I like. From IT to anything related to cars and / or electronics.

I’m mostly working with Typescript, Python, Rust and Zig as daily drivers. These help me to perform my tasks in full-stack web development, system development, gamedev and plenty of other tasks.

On the infrastructure side, I’m mostly using Terraform/OpenTofu, K8s and NixOS.





HackTheBox Badge TryHackMe Badge Contact Me

πŸ™‹ Father of useless web apps. I like programming, cybersecurity and electronics.

πŸ§‘β€πŸ’» Aiming at becoming a Cloud security architect. I work with Typescript, Python and Rust.

Otherwise, I like race cars. β˜•

PGP: DDF4 D46C DAAA 62C0 D71B 24EE 84E0 D9E9 1805 69EA