Google Closure Compiler and JSDoc Type Expression Parser

0.11.0 · maintenance · verified Sun Apr 19

Catharsis is a JavaScript library designed for parsing and manipulating type expressions used by Google Closure Compiler and JSDoc. It provides robust capabilities to convert these expressions into a structured Abstract Syntax Tree (AST), and then back into a string or a human-readable description. The current stable version is 0.11.0, last published about a year ago, indicating an irregular or maintenance-focused release cadence. Key differentiators include its high accuracy, backed by a Peggy grammar and a comprehensive test suite, and its flexibility in handling both standard Closure Compiler syntax and JSDoc-specific extensions like `string[]` for `Array<string>`. This library is primarily used by tools and systems that need to interpret or generate type annotations, offering programmatic access to the structure and meaning of complex type expressions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing both Closure Compiler and JSDoc-style type expressions, then stringifying and describing the results, including HTML-safe output.

import catharsis from 'catharsis';

// --- Closure Compiler Style Parsing ---
const closureType = '!Object';
let parsedClosureType;
try {
  parsedClosureType = catharsis.parse(closureType);
  console.log('Parsed Closure Type:', JSON.stringify(parsedClosureType));
  console.log('Stringified:', catharsis.stringify(parsedClosureType));
  console.log('Description:', catharsis.describe(parsedClosureType).simple);
} catch (e) {
  console.error(`Unable to parse '${closureType}':`, e.message);
}

// --- JSDoc Style Parsing (requires 'jsdoc: true') ---
const jsdocType = 'string[]'; // Equivalent to Closure Compiler's Array<string>
let parsedJsdocType;
try {
  parsedJsdocType = catharsis.parse(jsdocType, { jsdoc: true });
  console.log('Parsed JSDoc Type:', JSON.stringify(parsedJsdocType));
  console.log('Stringified:', catharsis.stringify(parsedJsdocType));
  console.log('Description:', catharsis.describe(parsedJsdocType).simple);
} catch (e) {
  console.error(`Unable to parse '${jsdocType}':`, e.message);
}

// --- HTML-safe Stringification ---
const typeWithGenerics = 'Array<number>';
const parsedGenerics = catharsis.parse(typeWithGenerics);
console.log('HTML-safe stringify:', catharsis.stringify(parsedGenerics, { htmlSafe: true }));

view raw JSON →