Importing Types in JSDoc
You'll learn: How to reference TypeScript types and interfaces from within JSDoc comments using @typedef and import() syntax.
Why Import Types in JSDoc?
When you're type-checking JavaScript files with JSDoc annotations, you often need to reference types defined elsewhere—either in TypeScript .ts files or other .d.ts declaration files. Instead of duplicating complex type definitions across multiple files, you can import them directly into your JSDoc comments.
Think of it like borrowing a blueprint from another building instead of redrawing it from scratch every time you need it.
The import() Syntax
JSDoc provides a special import() function (used only in comments, not at runtime) to pull in types from other modules:
/**
* @param {import('./types').User} user
*/
function greetUser(user) {
console.log(`Hello, ${user.name}`);
}
This references a User type exported from ./types.ts (or ./types.d.ts). The import path works just like regular JavaScript imports, but it only affects type-checking—nothing is imported at runtime.
Named vs Default Imports
You can import specific named types or default exports:
// Named type import
/** @type {import('./config').AppConfig} */
const config = loadConfig();
// Default export import
/** @type {import('./database').default} */
const db = createDatabase();
Using @typedef with Imported Types
You can create type aliases that reference imported types, making them easier to reuse within the same file:
/** @typedef {import('./models').Product} Product */
/** @typedef {import('./models').Category} Category */
/**
* @param {Product} product
* @param {Category} category
*/
function categorizeProduct(product, category) {
// Now you can use Product and Category without repeated imports
}
Importing Generics
When the imported type is generic, you can provide type arguments:
/**
* @type {import('./utils').Result<string, Error>}
*/
let result;
Key Takeaway: Use import('./module').TypeName syntax in JSDoc comments to reference TypeScript types from other files, avoiding duplication while maintaining type safety in JavaScript codebases during migration.