An ESLint custom parser which leverages TypeScript ESTree to enable ESLint linting of TypeScript source code
npx @tessl/cli install tessl/npm-typescript-eslint--parser@8.42.0The 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.
npm install @typescript-eslint/parserimport {
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");// eslint.config.js or .eslintrc.js
module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
sourceType: "module",
ecmaFeatures: {
jsx: true
}
}
};module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: __dirname,
sourceType: "module"
}
};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;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-eslint/typescript-estree to convert TypeScript AST nodes into ESTree-compatible format that ESLint can process@typescript-eslint/scope-manager to provide variable and reference tracking across TypeScript constructsThe parser operates in two primary modes:
tsconfig.json and provides full type information accessMain 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[];
}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;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;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'>;Package version and metadata constants.
/** Package version string */
const version: string;
/** Parser metadata for ESLint */
const meta: {
name: 'typescript-eslint/parser';
version: string;
};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;
}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;
}/** 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
}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 statementsimport { 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
}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
}
});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 informationProject Parsing (with project option):
tsconfig.jsonIsolated Parsing (without project option):
clearCaches() in long-running processes that lint many different projectswithoutProjectParserOptions() for batch processing to avoid memory buildupprojectService: true) can be more memory efficient for large codebases// 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
};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);
}tsconfig.json paths exist before using project optionerrorOnTypeScriptSyntacticAndSemanticIssues: false (default) to allow ESLint rules to handle errorsclearCaches() if experiencing memory-related errors in long-running processes