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

Type-Only Imports for Existing JS

Use import type to reference TypeScript types from JavaScript files without forcing full conversion.

Type-Only Imports for Existing JS

What you'll learn: How to reference TypeScript types from JavaScript files during migration without forcing immediate conversion.


When migrating a codebase gradually, you'll often need JavaScript files to reference types defined in TypeScript files—or vice versa. The problem? Regular imports create runtime dependencies that break if the imported module isn't fully converted yet. Type-only imports solve this by letting you use types for compile-time checking without affecting the runtime JavaScript at all.

The Migration Problem

Imagine you've created a TypeScript interface for your API responses, but your existing API client is still in JavaScript. You want type safety without rewriting everything at once. This is where import type becomes essential.

Using import type Syntax

The import type statement tells TypeScript: "I only need this for type-checking—strip it out completely at runtime."

// types.ts
export interface User {
  id: number;
  name: string;
  email: string;
}
// api.js (JavaScript file!)
// @ts-check

/**
 * @param {number} id
 * @returns {Promise<import("./types").User>}
 */
export async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

Notice the import("./types").User inside the JSDoc comment—this imports the type without any runtime impact.

Why This Matters During Migration

Type-only imports let you:

  • Add type safety to JS files without converting them to TypeScript
  • Reference TypeScript types from JavaScript code
  • Avoid circular dependencies during gradual conversion
  • Keep JavaScript files executable without a build step

Think of it like adding training wheels that don't change the bike—your JavaScript still runs normally, but TypeScript helps catch mistakes during development.

The Compile-Time vs Runtime Split

This is the key insight: types exist only during development. When TypeScript compiles or when your bundler processes files with isolatedModules, type-only imports vanish completely. Your JavaScript output contains no trace of them.

This separation lets you migrate incrementally—add types to document your code's shape without refactoring everything immediately.


Key Takeaway: Use import type (or JSDoc import() syntax) to reference TypeScript types from JavaScript files, enabling type safety during migration without forcing full conversion or creating runtime dependencies.