Casting and Type Assertions
You'll learn how to override JSDoc's inferred types when you know more than the type checker does.
The Core Idea
Sometimes JSDoc infers a type that's technically correct but too broad for your specific use case. Type casting (or type assertion) lets you tell the type checker: "Trust me, I know this value is more specific than you think." You're not changing the runtime value—just instructing the tooling to treat it as a narrower type.
Think of it like telling a security guard, "Yes, I know this box is labeled 'generic package,' but I packed it myself and I can confirm it contains books."
When You Need Casting
Common scenarios include:
- DOM queries that return generic
Elementwhen you know it's a specific element type - Functions returning broad unions when context guarantees one branch
- Third-party libraries with imprecise types
Syntax
Use @type in a special cast comment:
/** @type {HTMLInputElement} */
const input = document.querySelector('#username');
// Now 'input' is treated as HTMLInputElement, not Element | null
// Or inline cast:
const input = /** @type {HTMLInputElement} */ (document.querySelector('#username'));
You can also cast to union members:
/**
* @param {string | number} value
*/
function process(value) {
if (typeof value === 'string') {
/** @type {string} */
const str = value; // Explicitly narrow to string
console.log(str.toUpperCase());
}
}
Use Responsibly
Casts bypass type safety—if you're wrong, you won't get warnings. Only cast when you have runtime guarantees the type checker can't see.
Key Takeaway: Use JSDoc type casts (/** @type {SpecificType} */) to override inferred types when you have knowledge the type system doesn't, but always ensure your assertion matches runtime reality.