Registry / serialization / jsdoctypeparser

jsdoctypeparser

JSON →
library9.0.0jsnpmunverified

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.

npm install jsdoctypeparser
INSTALL
IMPORT
SIG · JSDOCTYPEPARSER
J
jsdoctypeparser
serializationjavascriptv9.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse
const { parse } = require('jsdoctypeparser');
import { parse } from 'jsdoctypeparser';
The package primarily exports CommonJS modules. Direct named ESM imports (e.g., `import { parse } from 'jsdoctypeparser';`) may not work as expected without a bundler or Node.js module interop configuration. If using ESM, try `import * as JSDocParser from 'jsdoctypeparser'; const { parse } = JSDocParser;`
publish
const { publish } = require('jsdoctypeparser');
import publish from 'jsdoctypeparser';
This function is a named export. Attempting a default import will fail. Refer to the `parse` import note for general CommonJS/ESM usage considerations.
traverse
const { traverse } = require('jsdoctypeparser');
import { traverse } from 'jsdoctypeparser/dist/traverse';
All public APIs are exposed directly from the main package entry point. Importing from internal paths (`/dist/traverse`) is not supported and may break across versions.
createDefaultPublisher
const { createDefaultPublisher } = require('jsdoctypeparser');
const createDefaultPublisher = require('jsdoctypeparser').createDefaultPublisher;
While the latter `require` syntax might work, destructuring (`const { ... } = require(...)`) is the idiomatic and recommended way to import named exports in CommonJS.

This quickstart demonstrates how to parse a JSDoc type expression into an AST, traverse the generated AST, and then stringify it back using `parse`, `traverse`, and `publish` functions.

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)}`);
Debug
Known issues
breakingThe 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.
fix
Consult the project's changelog or release notes for specific AST changes in each major version, and adapt AST processing logic accordingly. Be prepared for adjustments when upgrading.
affects: >=2.0.0
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.
fix
Always test with your specific type expressions. For ambiguous or complex types, simplify them if possible or consult the library's source/tests to understand its interpretation. The [live demo](https://jsdoctypeparser.github.io) is an excellent tool to quickly test expressions and view the resulting AST.
affects: >=1.0.0
gotchaWhile `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.
fix
When creating custom publishers, ensure comprehensive coverage for all `NodeType`s (inspect `lib/NodeType.js`). For AST modification and subsequent publishing, validate published output against expected string representations, especially after manual changes to the AST structure.
affects: >=1.0.0
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.
fix
Integrate with a separate type-checking solution (e.g., TypeScript, Closure Compiler, or custom linters) for semantic validation. Use `jsdoctypeparser` for understanding the *structure* of type annotations and enabling transformations, not for their runtime or compile-time validity.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Cannot find module 'jsdoctypeparser'
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.
fix
Install 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
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.
fix
Ensure 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]
The input type expression provided to the `parse()` function contains a syntax error or uses syntax that is not supported by `jsdoctypeparser`.
fix
Review 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.
Upgrade
Version history
9.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources