TypeScript API Utilities

2.5.0 · active · verified Sun Apr 19

ts-api-utils is a utility library providing helper functions for interacting with the TypeScript Compiler API. It serves as a modern successor to the widely used tsutils library, offering improved maintainability and updated conventions. The current stable version is 2.5.0, with a v3.0.0 release candidate recently published, indicating an active development cadence with regular updates. This library is crucial for tooling developers, static analysis tools, and code transformers that need to navigate and analyze TypeScript's Abstract Syntax Tree (AST) and type system. It aims to simplify common operations, making it easier to work with `ts.Node`, `ts.Type`, and `ts.Symbol` objects without directly reimplementing frequently needed logic. Its focus on providing a robust set of utilities for advanced TypeScript usage differentiates it from general-purpose utility libraries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a TypeScript file and using `ts-api-utils` type guards (`isIdentifier`, `isCallExpression`) to analyze its Abstract Syntax Tree (AST).

import ts from 'typescript';
import { isIdentifier, isCallExpression } from 'ts-api-utils';

function analyzeCode(code: string, fileName: string = 'test.ts') {
  const sourceFile = ts.createSourceFile(
    fileName,
    code,
    ts.ScriptTarget.ES2015,
    /*setParentNodes*/ true
  );

  let identifiersFound: string[] = [];
  let callExpressionsCount = 0;

  ts.forEachChild(sourceFile, function visitor(node: ts.Node) {
    if (isIdentifier(node)) {
      identifiersFound.push(node.text);
    } else if (isCallExpression(node)) {
      callExpressionsCount++;
    }
    ts.forEachChild(node, visitor); // Continue recursion
  });

  console.log(`Analyzed file: ${fileName}`);
  console.log(`Found identifiers: ${identifiersFound.join(', ')}`);
  console.log(`Found call expressions: ${callExpressionsCount}`);
}

const exampleCode = `
  function greet(name: string) {
    console.log("Hello, " + name + "!");
  }
  greet("World");
  const myVar = 123;
  const result = Math.max(myVar, 456);
`;

analyzeCode(exampleCode, 'example.ts');

view raw JSON →