Code Quality

Dead Code in TypeScript: Using the Compiler to Find It

TypeScript has compiler flags that detect dead code at compile time: noUnusedLocals, noUnusedParameters, and allowUnreachableCode.


❌ Unused Variables and Unreachable Code

function calculateDiscount(price: number, userId: string) {
  const unusedMultiplier = 1.5;  // Never used
  const user = fetchUser(userId);  // Result never used
  if (price > 100) return price * 0.9;
  else return price * 0.95;
  console.log('Done');  // Unreachable!
}

✅ Clean with Compiler Enforcement

// tsconfig.json: noUnusedLocals: true, noUnusedParameters: true

function calculateDiscount(price: number): number {
  if (price > 100) return price * 0.9;
  return price * 0.95;
}
💡

Pro tip: Use ts-prune to find unused exports across your entire project. Particularly useful before major refactors.

Paste this code into LearnCodeGuide

Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze TypeScript Code →

Related Guides

Typescript Any Type AbuseTypescript Type ErrorsJavascript Dead Code