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

The @ts-check Directive for File-Level Opt-In

Enable type-checking for individual JavaScript files using the @ts-check comment without project-wide checkJs.

The @ts-check Directive for File-Level Opt-In

What you'll learn: How to enable TypeScript's type-checking for individual JavaScript files without converting them to .ts or enabling project-wide checkJs.

What is @ts-check?

The @ts-check directive is a special comment you place at the top of a JavaScript file to tell TypeScript: "Please type-check this specific file, even though it's still .js."

Think of it like putting a "Please inspect" sticker on one package in a warehouse. You're not changing the entire warehouse policy—just asking for special attention on that one item.

Why This Matters During Migration

When migrating a large JavaScript codebase, you can't flip a switch and convert everything at once. The @ts-check directive lets you:

  • Test the waters on a file-by-file basis
  • Find type errors gradually without project-wide disruption
  • Keep files as JavaScript while gaining type safety
  • Avoid the checkJs: true commitment that affects your entire project

Basic Syntax

// @ts-check

// Now TypeScript will analyze this file
function greet(name) {
  return "Hello, " + name.toUppercase(); // Error: Property 'toUppercase' does not exist
}

greet(42); // Error: Argument of type 'number' not assignable to parameter of type 'string'

Just add // @ts-check as the very first line of your JavaScript file (before any code), and TypeScript starts analyzing it immediately.

How It Works with JSDoc

Since you're still in a .js file, you can combine @ts-check with JSDoc comments to provide explicit type information:

// @ts-check

/**
 * @param {string} name
 * @returns {string}
 */
function greet(name) {
  return "Hello, " + name;
}

greet(42); // Error: Argument of type 'number' not assignable to parameter of type 'string'

TypeScript uses both inference and your JSDoc annotations to understand what's happening.

When to Use @ts-check

This directive shines when:

  • You're migrating incrementally and want to start with low-risk files
  • You need to prove value before committing to full TypeScript
  • You want type safety without changing file extensions
  • You're working on a single problematic file that keeps causing bugs

The File-Level Advantage

Unlike checkJs: true in your tsconfig.json (which affects all JavaScript files), @ts-check is surgical. You control exactly which files get checked. This means:

  • No surprises across your codebase
  • Easier rollback (just remove one comment)
  • Team members can adopt at their own pace

Key Takeaway: The @ts-check directive enables TypeScript type-checking for individual JavaScript files, giving you a low-friction, file-by-file migration path without requiring project-wide configuration changes or file conversions.