or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-typescript-eslint--parser

An ESLint custom parser which leverages TypeScript ESTree to enable ESLint linting of TypeScript source code

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@typescript-eslint/parser@8.42.x

To install, run

npx @tessl/cli install tessl/npm-typescript-eslint--parser@8.42.0

index.mddocs/

TypeScript ESLint Parser

The TypeScript ESLint Parser is an ESLint custom parser that leverages TypeScript ESTree to enable ESLint linting of TypeScript source code. It serves as a bridge between ESLint's linting infrastructure and TypeScript's syntax analysis, providing type information and AST conversion capabilities.

Package Information

  • Package Name: @typescript-eslint/parser
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @typescript-eslint/parser

Core Imports

import { 
  parse, 
  parseForESLint, 
  ParserOptions,
  clearCaches,
  createProgram,
  withoutProjectParserOptions,
  ParserServices,
  ParserServicesWithTypeInformation,
  ParserServicesWithoutTypeInformation
} from "@typescript-eslint/parser";
import type * as ts from "typescript";
import type { TSESTree } from "@typescript-eslint/typescript-estree";

CommonJS:

const { parse, parseForESLint } = require("@typescript-eslint/parser");

Basic Usage

ESLint Configuration

// eslint.config.js or .eslintrc.js
module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    sourceType: "module",
    ecmaFeatures: {
      jsx: true
    }
  }
};

With TypeScript Project

module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    project: "./tsconfig.json",
    tsconfigRootDir: __dirname,
    sourceType: "module"
  }
};

Direct Parser Usage

import { parseForESLint } from "@typescript-eslint/parser";

const code = 'const greeting: string = "Hello, TypeScript!";';
const result = parseForESLint(code, {
  sourceType: "module",
  project: "./tsconfig.json"
});

const { ast, services, scopeManager, visitorKeys } = result;

Architecture

The TypeScript ESLint Parser serves as a critical bridge in the ESLint ecosystem, enabling ESLint to understand and lint TypeScript code. The parser's architecture consists of several key components:

  • TypeScript ESTree Integration: Leverages @typescript-eslint/typescript-estree to convert TypeScript AST nodes into ESTree-compatible format that ESLint can process
  • Scope Analysis: Uses @typescript-eslint/scope-manager to provide variable and reference tracking across TypeScript constructs
  • Type Information Access: When configured with a TypeScript project, provides access to TypeScript's type checker and symbol information
  • Performance Optimization: Supports both project-aware parsing (with type information) and isolated parsing (faster, without type information)
  • AST Mapping: Maintains bidirectional mappings between ESTree nodes and TypeScript AST nodes for seamless integration

The parser operates in two primary modes:

  1. Project Mode: Requires tsconfig.json and provides full type information access
  2. Isolated Mode: Parses individual files without project context for better performance

Capabilities

Core Parsing

Main parser functions for converting TypeScript code into ESLint-compatible AST.

/**
 * Parse TypeScript/JavaScript code and return just the AST
 * @param code - Source code string or TypeScript SourceFile
 * @param options - Parser configuration options
 * @returns ESLint-compatible AST
 */
function parse(
  code: string | ts.SourceFile,
  options?: ParserOptions
): ESLintProgram;

/**
 * Main parser function that returns complete result for ESLint
 * @param code - Source code string or TypeScript SourceFile  
 * @param parserOptions - Parser configuration options
 * @returns Complete parser result with AST, services, scope manager, and visitor keys
 */
function parseForESLint(
  code: string | ts.SourceFile,
  parserOptions?: ParserOptions | null
): ParseForESLintResult;

interface ParseForESLintResult {
  /** The parsed AST with ESLint-specific properties */
  ast: ESLintProgram;
  /** Scope analysis manager for variable and reference tracking */
  scopeManager: ScopeManager;
  /** Parser services for TypeScript type information access */
  services: ParserServices;
  /** Keys for AST traversal */
  visitorKeys: VisitorKeys;
}

interface ESLintProgram extends AST<{ comment: true; tokens: true }> {
  /** Array of comment nodes */
  comments: TSESTree.Comment[];
  /** Source location range */
  range: [number, number];
  /** Array of token nodes */
  tokens: TSESTree.Token[];
}

Cache Management

Utility function for clearing internal parser caches.

/**
 * Clears all internal parser caches used by the parser system
 * Clears: TSConfig resolution cache, program cache, watch caches, glob cache, 
 * project service cache, and default project matched files cache
 * Generally not needed in normal usage - intended for testing environments
 * or custom tooling that processes many projects to prevent memory leaks
 */
function clearCaches(): void;

TypeScript Program Creation

Utility for creating TypeScript programs from configuration files.

/**
 * Creates a TypeScript program from a TypeScript configuration file
 * @param configFile - Path to tsconfig.json file
 * @param projectDirectory - Optional project directory override
 * @returns TypeScript Program instance
 */
function createProgram(
  configFile: string,
  projectDirectory?: string
): ts.Program;

Parser Options Utilities

Utility for removing project-related options to enable faster isolated parsing.

/**
 * Removes options that prompt the parser to parse with type information
 * Use this for faster isolated file parsing without project context
 * @param opts - Original parser options
 * @returns Options with project-related fields removed
 */
function withoutProjectParserOptions<Options extends object>(
  opts: Options
): Omit<Options, 'EXPERIMENTAL_useProjectService' | 'project' | 'projectService'>;

Parser Metadata

Package version and metadata constants.

/** Package version string */
const version: string;

/** Parser metadata for ESLint */
const meta: {
  name: 'typescript-eslint/parser';
  version: string;
};

Configuration Options

interface ParserOptions {
  /** Allows additional properties for extensibility */
  [additionalProperties: string]: unknown;
  
  /** Source code type: 'script', 'module', or 'commonjs' */
  sourceType?: 'script' | 'module' | 'commonjs';
  
  /** ECMAScript version support */
  ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 
    | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026 
    | 'latest';
  
  /** ECMAScript feature configuration */
  ecmaFeatures?: {
    [key: string]: unknown;
    /** Enable global return statements */
    globalReturn?: boolean;
    /** Enable JSX parsing */
    jsx?: boolean;
  };
  
  /** TypeScript project configuration file path or boolean */
  project?: boolean | string | string[] | null;
  
  /** Root directory for TypeScript config resolution */
  tsconfigRootDir?: string;
  
  /** Provided TypeScript programs for parsing */
  programs?: ts.Program[] | null;
  
  /** Enable experimental decorators without project */
  experimentalDecorators?: boolean;
  
  /** Enable decorator metadata without project */
  emitDecoratorMetadata?: boolean;
  
  /** Enable isolated declarations mode */
  isolatedDeclarations?: boolean;
  
  /** Debug output configuration */
  debugLevel?: boolean | ('eslint' | 'typescript' | 'typescript-eslint')[];
  
  /** Allow TypeScript syntax and semantic errors */
  errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
  
  /** Cause parser to error on unknown AST node types */
  errorOnUnknownASTType?: boolean;
  
  /** Additional file extensions to parse */
  extraFileExtensions?: string[];
  
  /** File path for the code being parsed */
  filePath?: string;
  
  /** Library type definitions to include */
  lib?: string[];
  
  /** JSX pragma configuration */
  jsxPragma?: string | null;
  
  /** JSX fragment name configuration */
  jsxFragmentName?: string | null;
  
  /** JSDoc parsing mode configuration */
  jsDocParsingMode?: 'all' | 'none' | 'type-info';
  
  /** Include source ranges in AST nodes */
  range?: boolean;
  
  /** Include tokens in parser result */
  tokens?: boolean;
  
  /** Warn on unsupported TypeScript versions */
  warnOnUnsupportedTypeScriptVersion?: boolean;
  
  /** Project folders to ignore during project resolution */
  projectFolderIgnoreList?: string[];
  
  /** Project service configuration */
  projectService?: boolean | ProjectServiceOptions;
  
  /** Cache configuration */
  cacheLifetime?: {
    glob?: number | 'Infinity';
  };
}

interface ProjectServiceOptions {
  /** Files allowed with default project despite not matching */
  allowDefaultProject?: string[];
  
  /** Path to default TSConfig instead of TypeScript's default */
  defaultProject?: string;
  
  /** Whether to load TypeScript plugins from TSConfig */
  loadTypeScriptPlugins?: boolean;
  
  /** Maximum number of default project file matches */
  maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING?: number;
}

Parser Services

TypeScript type information services available when using project configuration.

/** Union type of parser services with or without type information */
type ParserServices = ParserServicesWithTypeInformation | ParserServicesWithoutTypeInformation;

/** Parser services available when TypeScript project is configured */
interface ParserServicesWithTypeInformation {
  /** TypeScript program instance */
  program: ts.Program;
  
  /** Get TypeScript symbol at ESTree node location */
  getSymbolAtLocation: (node: TSESTree.Node) => ts.Symbol | undefined;
  
  /** Get TypeScript type at ESTree node location */
  getTypeAtLocation: (node: TSESTree.Node) => ts.Type;
  
  /** Map from ESTree nodes to TypeScript nodes */
  esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, TSNode | TSToken>;
  
  /** Map from TypeScript nodes to ESTree nodes */
  tsNodeToESTreeNodeMap: WeakMap<TSNode | TSToken, TSESTree.Node>;
  
  /** Whether decorator metadata emission is enabled */
  emitDecoratorMetadata: boolean | undefined;
  
  /** Whether experimental decorators are enabled */
  experimentalDecorators: boolean | undefined;
  
  /** Whether isolated declarations mode is enabled */
  isolatedDeclarations: boolean | undefined;
}

/** Parser services available when no TypeScript project is configured */
interface ParserServicesWithoutTypeInformation {
  /** No TypeScript program available */
  program: null;
  
  /** Map from ESTree nodes to TypeScript nodes */
  esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, TSNode | TSToken>;
  
  /** Map from TypeScript nodes to ESTree nodes */
  tsNodeToESTreeNodeMap: WeakMap<TSNode | TSToken, TSESTree.Node>;
  
  /** Whether decorator metadata emission is enabled */
  emitDecoratorMetadata: boolean | undefined;
  
  /** Whether experimental decorators are enabled */
  experimentalDecorators: boolean | undefined;
  
  /** Whether isolated declarations mode is enabled */
  isolatedDeclarations: boolean | undefined;
}

Additional Types

/** Scope manager for variable and reference tracking */
interface ScopeManager {
  // Detailed scope analysis functionality from @typescript-eslint/scope-manager
}

/** Visitor keys for AST traversal */
interface VisitorKeys {
  // AST traversal keys from @typescript-eslint/visitor-keys  
}

/** TypeScript AST node types */
type TSNode = ts.Node;

/** TypeScript token types */
type TSToken = ts.Token;

/** AST type with specific options */
interface AST<T extends { comment: boolean; tokens: boolean }> {
  type: string;
  body: any[];
  sourceType: string;
  // Additional AST properties based on TypeScript ESTree
}

Usage Examples

Basic TypeScript Parsing

import { parseForESLint } from "@typescript-eslint/parser";

const typeScriptCode = `
interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Alice",
  age: 30
};
`;

const result = parseForESLint(typeScriptCode, {
  sourceType: "module"
});

console.log(result.ast.type); // "Program"
console.log(result.ast.body.length); // Number of top-level statements

With Type Information

import { parseForESLint } from "@typescript-eslint/parser";

const result = parseForESLint(code, {
  sourceType: "module",
  project: "./tsconfig.json",
  tsconfigRootDir: __dirname
});

if (result.services.program) {
  // Type information is available
  const typeChecker = result.services.program.getTypeChecker();
  
  // Use getTypeAtLocation and getSymbolAtLocation
  // to access TypeScript's type information
}

JSX Support

import { parseForESLint } from "@typescript-eslint/parser";

const jsxCode = `
const Component = () => {
  return <div>Hello, TypeScript + JSX!</div>;
};
`;

const result = parseForESLint(jsxCode, {
  sourceType: "module",
  ecmaFeatures: {
    jsx: true
  }
});

Isolated Parsing for Performance

import { parseForESLint, withoutProjectParserOptions } from "@typescript-eslint/parser";

const originalOptions = {
  sourceType: "module",
  project: "./tsconfig.json",
  tsconfigRootDir: __dirname
};

// Remove project options for faster parsing
const isolatedOptions = withoutProjectParserOptions(originalOptions);

const result = parseForESLint(code, isolatedOptions);
// This will be much faster but won't have type information

Performance Considerations

Project vs Isolated Parsing

Project Parsing (with project option):

  • Pros: Full type information access, complete semantic analysis, works with complex TypeScript features
  • Cons: Slower performance, higher memory usage, requires valid tsconfig.json
  • Use Case: Production linting where type information is needed for rules

Isolated Parsing (without project option):

  • Pros: Much faster parsing, lower memory footprint, no project setup required
  • Cons: No type information, limited to syntactic analysis only
  • Use Case: Quick syntax checking, development tools, CI environments where speed matters

Memory Management

  • Use clearCaches() in long-running processes that lint many different projects
  • Consider withoutProjectParserOptions() for batch processing to avoid memory buildup
  • Project service mode (projectService: true) can be more memory efficient for large codebases

Configuration Tips

// For maximum performance (syntax-only)
const fastOptions = {
  sourceType: "module",
  ecmaFeatures: { jsx: true }
  // No project option = faster parsing
};

// For full type information (slower but complete)
const completeOptions = {
  sourceType: "module",
  project: "./tsconfig.json",
  tsconfigRootDir: __dirname
};

Error Handling

Common Error Scenarios

Project Configuration Errors:

// Invalid tsconfig.json path
try {
  const result = parseForESLint(code, {
    project: "./invalid-tsconfig.json"
  });
} catch (error) {
  // Handle TSConfig resolution errors
  console.error("Failed to resolve TypeScript project:", error.message);
}

TypeScript Version Warnings:

// Suppress TypeScript version warnings
const result = parseForESLint(code, {
  warnOnUnsupportedTypeScriptVersion: false
});

Syntax Errors:

// TypeScript syntax errors in code
const invalidCode = "const x: = 123;"; // Invalid syntax
try {
  const result = parseForESLint(invalidCode);
} catch (error) {
  // Handle parsing errors
  console.error("Parse error:", error.message);
}

Error Prevention Tips

  • Always validate tsconfig.json paths exist before using project option
  • Use errorOnTypeScriptSyntacticAndSemanticIssues: false (default) to allow ESLint rules to handle errors
  • Test parser options with sample files before processing large codebases
  • Use clearCaches() if experiencing memory-related errors in long-running processes