ts-analyzer is a high-performance static code analysis tool designed to inspect, measure, and optimize TypeScript and JavaScript codebases. By performing AST (Abstract Syntax Tree) analysis on your source files, it calculates your type coverage, computes a custom type safety score, measures cyclomatic complexity, identifies duplicate code, and flags code smells / anti-patterns.
Upgrade your code quality tracking beyond simple line counting to comprehensive structural analysis.
- Key Features
- Why ts-analyzer? (Comparison)
- How It Works
- Quick Start Guide
- Configuration (
ts-analyzer.config.json) - Example Report Formats
- CI/CD Pipeline Integration
- Development & Testing
- Frequently Asked Questions (FAQ)
- License
- 📊 Type Safety & Coverage Analysis: Computes your actual type coverage, penalizing overused
anydeclarations, generic safety lapses, and raw type assertions. - 📉 Cyclomatic Complexity Measurement: Analyzes structural paths in your control flow graph to rate how maintainable and testable your functions are.
- 🔍 Code Smell & Anti-Pattern Detection: Automatically flags Callback Hell, Magic Numbers, Excessive Parameters (>4), and "God Files" (>500 lines).
- 👯 Duplicate Code Finder: Scans files for structural duplicates and cloned logic blocks across your codebase.
- 📋 Multiple Output Formats: Supports clean terminal tables (
text), structured data (json), or interactive HTML dashboards (html). - ⚡ Strict tsconfig Checker: Evaluates configuration flags (
strict,noImplicitAny, etc.) and awards bonus points for stricter setups.
Standard linting tools like ESLint and formatting tools like Prettier check code formatting and basic rules, but don't give you a unified health score or complexity map.
| Feature / Metric | ts-analyzer |
ESLint | react-loc-analyzer |
|---|---|---|---|
| AST-Based Type Coverage | Yes | No | No |
| Cyclomatic Complexity Rating | Yes | Yes (Rules) | No |
| Unified Type Safety Score | Yes | No | No |
| Duplicate Code Scan | Yes | No | No |
| Interactive HTML Reports | Yes | No | No |
| Line Counter | Yes | No | Yes |
The tool utilizes TypeScript's compiler API to parse files into AST nodes, separating explicit types from implicit/inferred ones.
┌─────────────────────┐
│ TypeScript Files │
└─────────┬───────────┘
│
▼
┌─────────────────────┐ ┌─────────────────────┐
│ AST Analysis │───>│ Node Classification │
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ Explicitly Typed │ │ Implicitly Typed │
│ Nodes │ │ Nodes │
└─────────┬───────────┘ └─────────┬───────────┘
│ │
└──────────┬──────────────┘
│
▼
┌─────────────────────┐ ┌─────────────────────┐
│ Type Coverage │<───│ tsconfig.json │
│ Calculation │ │ Analysis │
└─────────┬───────────┘ └─────────────────────┘
│
▼
┌─────────────────────┐
│ "any" & Assertion │
│ Penalty Calculation │
└─────────┬───────────┘
│
▼
┌─────────────────────┐
│ Final Type Safety │
│ Score & Rating │
└─────────────────────┘
- Formula: The final score is based on the percentage of typed nodes, minus penalty weights for every instance of
any,as Typeassertions, and non-null assertions (!). - tsconfig.json Influence: Active compiler configurations such as
strict: trueornoImplicitAny: trueboost the overall rating.
ts-analyzer calculates a score for function and structural complexity:
- Cyclomatic Complexity: Measures independent execution paths (conditions, loops). Ratings:
<30(Simple),30-60(Moderate),>60(High Complexity). - Nesting Depth: Highlights highly nested code blocks to help developers avoid "Callback Hell".
- Function Arguments: Flags functions with more than 4 parameters.
- Duplicate Code Detection: Identifies structurally identical sequences of code in different files.
You can run ts-analyzer directly using npx without local installation:
npx ts-analyzer /path/to/projectOr install it globally:
npm install -g ts-analyzer
ts-analyzer /path/to/project| Option | Shortcut | Description |
|---|---|---|
--format <type> |
-f |
Output format: text, json, html, or context |
--exclude <folders> |
-e |
Folders to ignore, comma-separated (e.g. node_modules,dist,.next) |
--no-safety |
Skip TypeScript type safety calculations for faster runs | |
--no-complexity |
Skip code complexity and anti-pattern analysis | |
--init-rules [type] |
Generate customized AI coding rules (cursorrules, claudeprompt, or both) |
To standardize run settings in your repository, create a ts-analyzer.config.json file in your project root:
{
"safety": true,
"complexity": true,
"format": "text",
"exclude": ["node_modules", "dist", ".next", "coverage"],
"include": [".js", ".jsx", ".ts", ".tsx"]
}Generate structured analysis data using -f json:
{
"files": 156,
"totalLines": 15234,
"codeLines": 12845,
"typescriptSafety": {
"tsPercentage": "84.6",
"avgTypeCoverage": "92.3",
"totalAnyCount": 12,
"avgTypeSafetyScore": 85,
"overallComplexity": "Low"
},
"codeComplexity": {
"avgComplexity": "3.2",
"maxComplexity": 12,
"overallComplexity": "Low",
"codeSmells": {
"magicNumbers": 0,
"callbackHell": 0,
"excessiveParameters": 0,
"godFiles": 0
},
"duplicateCode": {
"totalClones": 2,
"totalDuplicateLines": 24,
"clones": []
}
}
}Generate a responsive web dashboard using -f html which saves as ts-analyzer-report.html. It provides:
- Project Summary Cards: Visual highlights of total files, line counts, and comments.
- Type Safety Score Progress Bars: Quick visual representation of code safety levels.
- Code Smell Warning Badges: Colored status flags indicating potential structural design issues.
Generate a condensed outline of the project's types, exports, and relationships using -f context. This outline tree is optimized to give chat LLMs (such as Cursor, Claude, or Gemini) deep system context in a single small file, avoiding token bloat:
ts-analyzer -f context > project-context.mdCreate custom editor rule files (.cursorrules or .claudeprompt) tailored specifically to the metrics and health of your codebase:
ts-analyzer --init-rules bothThis command analyzes your code quality metrics (e.g., cyclomatic complexity, nesting depth, type safety score) and builds strict, contextual prompts guiding your AI editor to write clean, type-safe, and low-complexity code from day one.
Add static analysis checks directly to your GitHub Action workflows:
name: Code Quality Check
on: [push, pull_request]
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Run ts-analyzer
run: npx ts-analyzer . --format textWe welcome community contributions. To set up the project locally:
# Clone the repository
git clone https://github.com/amir-valizadeh/ts-analyzer.git
cd ts-analyzer
# Install dependencies
npm install
# Run unit and integration tests (Vitest)
npm test
# Generate test coverage
npm run test:coverage- Type Coverage is the percentage of AST nodes that have an explicit or successfully inferred type associated with them.
- Type Safety Score starts at your coverage rate and subtracts penalties for "unsafe" practices like raw
anytypes,astype assertions, and non-null assertions (!). It also factors in yourtsconfig.jsoncompiler flags.
It traverses the Abstract Syntax Tree (AST) of each function and adds weight for every branching point (e.g. if, else, switch cases, loops like for/while, and conditional expressions).
Yes! ts-analyzer fully supports JavaScript projects. It parses .js and .jsx files and calculates metrics like cyclomatic complexity, nested blocks, and duplicate code. The TypeScript-specific checks (e.g., type safety score) are skipped automatically.
TypeScript compiles down to plain JavaScript, stripping away type declarations at runtime. Static analysis using ts-analyzer helps you catch structural design bugs and check type safety before compilation, ensuring high runtime safety.
This project is licensed under the MIT License. See the LICENSE file for more information.