JSDoc Type Expression Parser

9.0.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

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)}`);

view raw JSON →