Course contentsShow
← TypeScript
Lesson 1617 of 1,79637. Migrating JavaScript to TypeScriptFree lesson

Managing the JS/TS Boundary

How TypeScript treats imports from .js files and strategies for typing the interface between old and new code.

Managing the JS/TS Boundary

What you'll learn: How TypeScript treats imports from .js files and the strategies you need to safely type the interface between your old JavaScript code and new TypeScript code during migration.

The Import Boundary Challenge

When you enable allowJs, TypeScript allows .ts files to import from .js files. But here's the critical question: what types does TypeScript assign to values coming from JavaScript?

The answer determines how safe your migration boundary is.

How TypeScript Treats JavaScript Imports

By default, TypeScript applies inference to JavaScript files when imported:

  • Variables, function return values, and parameters get basic type inference
  • If inference fails, TypeScript falls back to any
  • Without checkJs, TypeScript trusts whatever it infers without validation

This creates a dangerous zone: you think you have types, but they may be inaccurate guesses. A JavaScript function might return different types in different code paths, but TypeScript only sees one call site.

Strategy 1: Explicit Interface Definitions

Create .d.ts files or type declarations at the boundary:

Define the contract you expect from your JavaScript modules explicitly. Don't rely on inference. This acts as a type firewall—the TypeScript side works with known types, and if the JavaScript breaks the contract, you catch it at the boundary.

Strategy 2: Treat JS Imports as unknown

For critical boundaries, import JavaScript values and immediately narrow them with type guards or validation. This prevents implicit any from leaking through your codebase.

Strategy 3: Enable checkJs Selectively

Use @ts-check in critical JavaScript files to get type-checking without converting them. This validates that your type assumptions about the JS/TS boundary are correct.

The Gradual Typing Sweet Spot

The safest boundary management combines:

  • Explicit type definitions for JS imports
  • Type guards or validation at entry points
  • Incremental checkJs on foundational JavaScript files
  • Clear team conventions about which strategy applies where

Key Takeaway: The JS/TS boundary is your migration's weak point—TypeScript's inference from JavaScript is optimistic at best. Defend it with explicit types, validation, or selective checkJs to prevent any from undermining your TypeScript safety guarantees.