Sub topic 9
Sharing Types Across Files
Real projects spread their types over many modules. A User shape defined in user.js is needed in describe.js, api.js, and a dozen other places. Copying the @typedef into each file works for a week. Then someone adds a field to one copy and forgets the others. This chapter shows how to define a type once and reference it from any file using import() type expressions and the newer @import tag.
This chapter assumes you have read the earlier chapters on @typedef, @callback, and @template. It also assumes your project is set up for type checking with // @ts-check or checkJs, as covered in the previous chapter. Without a type checker, import() types are still readable documentation, but nothing confirms that they point at a real type.
How JSDoc Types Become Exportable
The TypeScript checker treats every top-level @typedef and @callback in a module as an exported type. A module is any file that contains at least one import or export statement. You don't write export on the typedef itself. Being at the top level of a module is enough.
// src/user.js
/**
* @typedef {Object} User
* @property {string} id - Unique identifier.
* @property {string} name - Display name.
* @property {string} [email] - Optional email address.
*/
/**
* Creates a user with a generated id.
* @param {string} name
* @returns {User}
*/
export function createUser(name) {
return { id: crypto.randomUUID(), name };
}The file exports createUser at runtime and User as a type. The type disappears when the code runs, because it only ever lived in a comment.
The import() Type Expression
To use User in another file, write an import() type expression. Its form is import('path').Name. The path follows the same resolution rules as a real import statement in that file.
// src/describe.js
/** @typedef {import('./user.js').User} User */
/**
* Formats a user for display.
* @param {User} user
* @returns {string}
*/
export function describe(user) {
return `${user.name} (${user.id})`;
}The @typedef line creates a local alias, so the rest of the file can write {User} instead of repeating the full expression. You can also put the expression inline when you need it only once:
// src/greet.js
/**
* @param {import('./user.js').User} user
* @returns {string}
*/
export function greet(user) {
return `Hello, ${user.name}`;
}Inline expressions are fine for a single use. Once a type shows up more than twice in a file, the alias reads better and leaves one line to change if the path moves.
Generic types across files
If the imported typedef has a @template, pass type arguments after the name, just as you would locally:
// src/result.js
/**
* @template T
* @typedef {{ ok: true, value: T } | { ok: false, error: string }} Result
*/
export {};// src/load.js
/** @typedef {import('./user.js').User} User */
/** @typedef {import('./result.js').Result<User>} UserResult */
/**
* @param {string} name
* @returns {UserResult}
*/
export function loadUser(name) {
if (!name) return { ok: false, error: 'name is required' };
return { ok: true, value: { id: '1', name } };
}result.js contains only types, so it ends with export {}; to stay a module.
The @import Tag
TypeScript 5.5 added an @import tag whose syntax matches an ES import statement. It takes the place of a stack of @typedef {import(...)} aliases:
// src/report.js
/** @import { User } from './user.js' */
/** @import { Result } from './result.js' */
/**
* @param {Result<User>[]} results
* @returns {User[]}
*/
export function successful(results) {
/** @type {User[]} */
const users = [];
for (const r of results) {
if (r.ok) users.push(r.value);
}
return users;
}Several names can share one tag (@import { User, Admin } from './user.js'), and the namespace form works too (@import * as models from './models.js', then {models.User}). Like import() types, @import produces nothing at runtime.
Types From Values: typeof import()
import('./x.js').Name looks up a type named Name. Sometimes you want the type of a value instead, such as a module's exports, a config object, or a class constructor. Add typeof:
// src/config.js
export const defaults = {
retries: 3,
timeoutMs: 5000,
};// src/client.js
/** @typedef {typeof import('./config.js').defaults} Config */
/** @typedef {typeof import('./config.js')} ConfigModule */
/**
* @param {Partial<Config>} overrides
* @returns {Config}
*/
export function makeConfig(overrides) {
return { retries: 3, timeoutMs: 5000, ...overrides };
}Config is the inferred type { retries: number; timeoutMs: number }, so you never write that shape by hand. Add a field to defaults and Config picks it up automatically.
Classes need care, because a class name refers to two things. Assume Counter is the class from the classes chapter, exported from src/counter.js:
| Expression | Meaning | Typical use |
|---|---|---|
| `import('./counter.js').Counter` | An instance of the class | A parameter that receives a counter |
| `typeof import('./counter.js').Counter` | The class itself (the constructor) | A factory that receives the class |
| `typeof import('./counter.js')` | The whole module's exports | Dependency injection, mocks |
// src/factory.js
/** @typedef {import('./counter.js').Counter} Counter */
/**
* @param {typeof import('./counter.js').Counter} CounterClass
* @returns {Counter}
*/
export function makeCounter(CounterClass) {
return new CounterClass(10);
}Types From Packages
The path in import() can be a package name. The checker finds the package's own type declarations or the matching @types/* package:
// src/server.js
import { createServer } from 'node:http';
/**
* @param {import('node:http').IncomingMessage} req
* @param {import('node:http').ServerResponse} res
*/
function handle(req, res) {
res.end(`You asked for ${req.url}`);
}
createServer(handle).listen(3000);Run npm install --save-dev @types/node so the checker can resolve node:http. Without type declarations the import resolves to any (or reports an error under strict settings), and the annotation silently stops checking anything.
How Resolution Works
Path resolution follows your tsconfig.json settings, so write the path the way you would write a runtime import in the same project. In Node ES module projects ("module": "nodenext"), relative paths need the .js extension, so import('./user') fails where import('./user.js') succeeds. Bundler-style settings allow paths without the extension. Choose one style and use it in comments and code alike.
Type Imports Don't Create Runtime Dependencies
A useful property of import() types and @import is that they are erased. They never load the target module, so they cannot cause circular-dependency bugs at runtime.
Say order.js needs the User type and user.js needs the Order type. If each file did import { User } from './user.js' only to get a type, you would add a runtime cycle, and in a JavaScript file you can't import a typedef that way anyway. With type imports, both files reference each other freely:
// src/order.js
/** @import { User } from './user.js' */
/**
* @typedef {Object} Order
* @property {string} id
* @property {User} buyer
*/
export {};The rule follows from that: import a value with a real import when you call it at runtime, and use a type import when you only need its type.
Organizing Shared Types
Two layouts are common, and both work well:
- Co-located types. Each typedef lives next to the code that creates it (
Userinuser.js). Readers find the type where the behavior is. This fits most application code. - A types module. Shapes shared across many modules, such as API payloads and event objects, go in
src/types.jsending withexport {};. This works well for cross-cutting contracts with no single owner.
Some projects put shared types in a .d.ts file and import them the same way (import('./types').ApiError; leave off the extension for .d.ts targets, or point at the .js path the declaration describes). This allows full TypeScript syntax, but it adds a second language to the codebase. Reach for it only when JSDoc can't express a type you need.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `File '.../types.js' is not a module` | Types-only file has no import or export | Add `export {};` |
| `Module has no exported member 'User'` | Typedef is nested inside a function or block, or the name is misspelled | Move the typedef to the top level; check spelling and case |
| `Cannot find module './user'` | Missing extension under `nodenext` resolution | Write `./user.js` |
| Type silently becomes `any` | Package has no type declarations | Install `@types/...`, or turn on `noImplicitAny` to surface it |
| Instance methods missing on a "class" type | Used `typeof import(...).Cls` where an instance was meant | Drop `typeof` |
| jsdoc HTML build logs `Invalid type expression` | The classic jsdoc parser does not understand `import()` | Use a plugin that rewrites import types, covered in the documentation-site chapter |
| eslint-plugin-jsdoc flags valid `import()` types | Plugin is in `jsdoc` or `closure` mode | Set `settings.jsdoc.mode` to `"typescript"` |
The last two rows matter because the import() syntax comes from TypeScript, not from the original JSDoc specification. The type checker and editors understand it natively. Other tools that parse your comments may need configuration first.
Exercises
Exercise
src/types.js contains only /** @typedef {{ x: number, y: number }} Point */. In src/geo.js, /** @param {import('./types.js').Point} p */ reports "File is not a module". Why, and what is the smallest fix?
Show answer
types.js has no import or export statement, so TypeScript treats it as a script. Its typedef becomes a global type and is not exported, so import() cannot resolve it. Add export {}; to types.js to make it a module. Point is then exported automatically.
Exercise
src/plugins.js exports class Plugin {}. Write the JSDoc for a function register(PluginClass) that receives the class itself and returns an instance of it, importing the type from ./plugins.js.
Show answer
Use typeof for the constructor and the plain name for the instance: /** @param {typeof import('./plugins.js').Plugin} PluginClass @returns {import('./plugins.js').Plugin} */, with each tag on its own line, followed by function register(PluginClass) { return new PluginClass(); }.
Exercise
invoice.js and customer.js each need the other's typedef. A teammate suggests adding import './customer.js' to invoice.js so the types are visible. What is the problem, and what should be used instead?
Show answer
A real import creates a runtime dependency and a circular import between the two modules. It also doesn't bring a JSDoc typedef into scope. Use type-only references, /** @typedef {import('./customer.js').Customer} Customer */ or /** @import { Customer } from './customer.js' */. These are erased at runtime, so the cycle exists only for the type checker, which handles it without trouble.