---
name: typescript-circular-dependency
description: |-
  Detect and resolve TypeScript/JavaScript circular import dependencies. Use when:
  (1) "Cannot access 'X' before initialization" at runtime, (2) Import returns 
  undefined unexpectedly, (3) "ReferenceError: Cannot access X before initialization",
  (4) Type errors that disappear when you change import order, (5) Jest/Vitest tests 
  fail with undefined imports that work in browser.
author: Claude Code
version: 1.0.0
date: 2024-03-10
title: typescript-circular-dependency
canonical_url: https://skilld.dev/gh/blader/claudeception/typescript-circular-dependency
last_updated: 2026-10-09T02:30:27.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install blader/claudeception/typescript-circular-dependency`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/typescript-circular-dependency`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/blader/claudeception/typescript-circular-dependency) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/typescript-circular-dependency`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/typescript-circular-dependency --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/typescript-circular-dependency --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# TypeScript Circular Dependency Detection and Resolution

## Problem

Circular dependencies occur when module A imports from module B, which imports 
(directly or indirectly) from module A. TypeScript compiles successfully, but at 
runtime, one of the imports evaluates to `undefined` because the module hasn't 
finished initializing yet.

## Context / Trigger Conditions

Common error messages:

```
ReferenceError: Cannot access 'UserService' before initialization
```

```
TypeError: Cannot read properties of undefined (reading 'create')
```

```
TypeError: (0 , _service.doSomething) is not a function
```

Symptoms that suggest circular imports:

- Import is `undefined` even though the export exists
- Error only appears at runtime, not during TypeScript compilation
- Moving an import statement changes which import is undefined
- Tests fail but the app works (or vice versa)
- Adding `console.log` at the top of a file changes behavior

## Solution

### Step 1: Detect the Cycle

Use a tool to visualize dependencies:

```bash
# Install madge
npm install -g madge

# Find circular dependencies
madge --circular --extensions ts,tsx src/

# Generate visual graph
madge --circular --image graph.svg src/
```

Or use the TypeScript compiler:

```bash
# Check for cycles (requires tsconfig setting)
npx tsc --listFiles | head -50
```

### Step 2: Identify the Pattern

Common circular dependency patterns:

**Pattern A: Service-to-Service**
```
services/userService.ts → services/orderService.ts → services/userService.ts
```

**Pattern B: Type imports**
```
types/user.ts → types/order.ts → types/user.ts
```

**Pattern C: Index barrel files**
```
components/index.ts → components/Button.tsx → components/index.ts
```

### Step 3: Resolution Strategies

**Strategy 1: Extract Shared Dependencies**

Before:
```typescript
// userService.ts
import { OrderService } from './orderService';
export class UserService { ... }

// orderService.ts  
import { UserService } from './userService';
export class OrderService { ... }
```

After:
```typescript
// types/interfaces.ts (new file - no imports from services)
export interface IUserService { ... }
export interface IOrderService { ... }

// userService.ts
import { IOrderService } from '../types/interfaces';
export class UserService implements IUserService { ... }
```

**Strategy 2: Dependency Injection**

```typescript
// orderService.ts
export class OrderService {
  constructor(private userService: IUserService) {}
  
  // Instead of importing UserService directly
}

// main.ts
const userService = new UserService();
const orderService = new OrderService(userService);
```

**Strategy 3: Dynamic Imports**

```typescript
// Only import when needed, not at module level
async function processOrder() {
  const { UserService } = await import('./userService');
  // ...
}
```

**Strategy 4: Use Type-Only Imports**

If you only need types (not values), use type-only imports:

```typescript
// This doesn't create a runtime dependency
import type { User } from './userService';
```

**Strategy 5: Restructure Barrel Files**

Before (problematic):
```typescript
// components/index.ts
export * from './Button';
export * from './Modal';  // Modal imports Button from './index'
```

After:
```typescript
// components/Modal.tsx
import { Button } from './Button';  // Direct import, not from index
```

### Step 4: Prevent Future Cycles

Add to your CI/build process:

```json
// package.json
{
  "scripts": {
    "check:circular": "madge --circular --extensions ts,tsx src/"
  }
}
```

Or configure ESLint:

```javascript
// .eslintrc.js
module.exports = {
  plugins: ['import'],
  rules: {
    'import/no-cycle': ['error', { maxDepth: 10 }]
  }
}
```

## Verification

1. Run `madge --circular src/` - should report no cycles
2. Run your test suite - previously undefined imports should work
3. Delete `node_modules` and reinstall - app should still work
4. Build for production - no runtime errors

## Example

**Problem**: `OrderService` is undefined when imported in `UserService`

**Detection**:
```bash
$ madge --circular src/
Circular dependencies found!
  src/services/userService.ts → src/services/orderService.ts → src/services/userService.ts
```

**Fix**: Extract shared interface

```typescript
// NEW: src/types/services.ts
export interface IOrderService {
  createOrder(userId: string): Promise<Order>;
}

// MODIFIED: src/services/userService.ts
import type { IOrderService } from '../types/services';

export class UserService {
  constructor(private orderService: IOrderService) {}
}

// MODIFIED: src/services/orderService.ts  
// No longer imports UserService
export class OrderService implements IOrderService {
  async createOrder(userId: string): Promise<Order> { ... }
}
```

## Notes

- TypeScript `import type` is your friend—it's erased at runtime and can't cause cycles
- Barrel files (`index.ts`) are a common source of accidental cycles
- The order of exports in a file can matter when there's a cycle
- Jest/Vitest may handle module resolution differently than your bundler
- Some bundlers (Webpack, Vite) have better cycle handling than others
- `require()` can sometimes mask circular dependency issues that `import` exposes
