JSDoc Type Expression Parser
The `jsdoctypeparser` library provides a strict parser for various JavaScript type expression syntaxes, including JSDoc, Closure Compiler, and a subset of TypeScript types. It is currently at version 9.0.0. The library transforms these type expressions into a detailed Abstract Syntax Tree (AST), enabling programmatic analysis and manipulation. It also offers a `publish` function to stringify an AST back into a type expression, with capabilities for custom stringification via a publisher API. Additionally, a `traverse` function allows for AST navigation with `onEnter` and `onLeave` handlers. This tool is crucial for projects needing to deeply understand, validate, or transform JSDoc-style type annotations, serving as a foundational component for linters, documentation generators, and code transformation tools. Its differentiators lie in its strict parsing capabilities across multiple dialects and its comprehensive AST manipulation utilities, which allow for a high degree of control over type expression processing. The project maintains an active development status, focusing on robustness and specification adherence.
Common errors
-
Error: Cannot find module 'jsdoctypeparser'
cause The package is not installed in your project's `node_modules` directory, or there's a typo in the module name in your `require()` or `import` statement.fixInstall the package using your preferred package manager: `npm install jsdoctypeparser` or `yarn add jsdoctypeparser`. Double-check the module name in your code. -
TypeError: parse is not a function
cause Attempting to use `parse` (or other named exports) as a default import or accessing it incorrectly from the `require()` call, especially when trying to use ESM-style imports (`import { parse } from '...'`) with this CommonJS-first library without proper tooling.fixEnsure you are using the correct CommonJS destructuring: `const { parse } = require('jsdoctypeparser');`. If you are in an ESM context, you might need `import * as JSDocParser from 'jsdoctypeparser'; const { parse } = JSDocParser;` or ensure your build tools (e.g., Webpack, Rollup) are configured for CommonJS interop. -
Error: Failed to parse the type expression: [Your Expression]
cause The input type expression provided to the `parse()` function contains a syntax error or uses syntax that is not supported by `jsdoctypeparser`.fixReview your type expression for grammatical correctness based on JSDoc, Closure Compiler, or the supported TypeScript type subset. Test the problematic expression directly in the [jsdoctypeparser live demo](https://jsdoctypeparser.github.io) to quickly identify the exact parsing error and expected AST.
Warnings
- breaking The Abstract Syntax Tree (AST) structure generated by `parse()` may undergo breaking changes in major version releases. Consumers of the AST should test thoroughly when upgrading to a new major version, as node types, property names, or overall tree shape might be altered to support new syntax or improve internal representation.
- gotcha `jsdoctypeparser` supports JSDoc, Closure Compiler, and some TypeScript types, but full compatibility with all nuances of each specification, especially TypeScript, is not guaranteed. Subtle differences in how each standard defines or interprets certain expressions might lead to unexpected ASTs or parsing failures for very specific edge cases.
- gotcha While `publish()` can stringify ASTs, direct manipulation of the AST and then publishing might not always produce the exact original string unless the modifications are well-understood. Custom publishers created with `createDefaultPublisher` require handlers for *all* node types, which can be verbose and error-prone if not all types are explicitly handled, leading to unexpected output or errors.
- gotcha `jsdoctypeparser` is a lexical and syntactical parser; it converts type expressions into a structured Abstract Syntax Tree. It does not perform semantic analysis, type validation, or type checking against an actual codebase. It cannot determine if a parsed type 'exists' or is 'correct' in the context of your project.
Install
-
npm install jsdoctypeparser -
yarn add jsdoctypeparser -
pnpm add jsdoctypeparser
Imports
- parse
import { parse } from 'jsdoctypeparser';const { parse } = require('jsdoctypeparser'); - publish
import publish from 'jsdoctypeparser';
const { publish } = require('jsdoctypeparser'); - traverse
import { traverse } from 'jsdoctypeparser/dist/traverse';const { traverse } = require('jsdoctypeparser'); - createDefaultPublisher
const createDefaultPublisher = require('jsdoctypeparser').createDefaultPublisher;const { createDefaultPublisher } = require('jsdoctypeparser');
Quickstart
const { parse, publish, traverse } = require('jsdoctypeparser');
// 1. Parse a complex JSDoc type expression into an AST
const typeExpression = 'Array<{ key1: function(number): string, key2: A.B.C | null }>';
console.log(`Parsing: ${typeExpression}`);
const ast = parse(typeExpression);
console.log('Generated AST (partial):', JSON.stringify(ast, null, 2).substring(0, 200) + '...');
// 2. Traverse the AST to log node types and their parentage
console.log('\n--- Traversing AST ---');
traverse(ast,
(node, parentKey, parentNode) => {
const parentInfo = parentNode ? `${parentNode.type} (key: ${parentKey})` : 'none';
console.log(` Enter: ${node.type} (parent: ${parentInfo})`);
},
(node) => console.log(` Leave: ${node.type}`)
);
console.log('--- End Traversal ---\n');
// 3. Stringify the AST back into a type expression
const stringified = publish(ast);
console.log(`Stringified AST back to: ${stringified}`);
// Example with a simpler AST for publishing
const simpleAst = { type: 'NAME', name: 'MySimpleType' };
console.log(`\nStringifying simple AST: ${JSON.stringify(simpleAst)} -> ${publish(simpleAst)}`);