Combining @ts-check with JSDoc Annotations
What you'll learn: How to layer explicit JSDoc type annotations on top of @ts-check to provide clarity where TypeScript's inference falls short.
The Power of Dual Strategies
You've learned that @ts-check enables TypeScript's type-checking engine in JavaScript files, and you know how to write JSDoc annotations to describe types explicitly. When you combine these two tools, you get the best of both worlds: automatic inference where it works, and explicit type documentation where it doesn't.
Think of @ts-check as a smart assistant that makes educated guesses about your types. Most of the time it's right, but sometimes it needs your help—that's where JSDoc comes in.
When Inference Needs Help
TypeScript inference works great for simple cases like const x = 5 (clearly a number). But it struggles with:
- Empty arrays (
[]could hold anything) - Function parameters (no clue what you'll pass)
- Complex object shapes
- External API responses
By adding JSDoc annotations at these friction points, you guide the type checker without rewriting your entire codebase in TypeScript.
The Workflow
// @ts-check
// Inference alone: TypeScript guesses 'any[]'
const items = [];
// Adding JSDoc: Now it knows!
/** @type {string[]} */
const names = [];
// Parameters need explicit types
/**
* @param {number} age
* @returns {boolean}
*/
function isAdult(age) {
return age >= 18;
}
With this combination, you catch errors during development while keeping your code in plain JavaScript. You selectively annotate only what needs clarification.
The Sweet Spot
This approach is perfect for gradually improving type safety in existing projects. You don't need to convert to .ts files—just add @ts-check at the top and sprinkle JSDoc where the checker complains or where clarity helps your team.
Key Takeaway: Combining @ts-check with JSDoc annotations gives you surgical type safety—automatic inference handles the obvious cases while explicit annotations guide the checker through the complex ones.