0
# TypeScript ESLint Parser
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: @typescript-eslint/parser
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @typescript-eslint/parser`
10
11
## Core Imports
12
13
```typescript
14
import {
15
parse,
16
parseForESLint,
17
ParserOptions,
18
clearCaches,
19
createProgram,
20
withoutProjectParserOptions,
21
ParserServices,
22
ParserServicesWithTypeInformation,
23
ParserServicesWithoutTypeInformation
24
} from "@typescript-eslint/parser";
25
import type * as ts from "typescript";
26
import type { TSESTree } from "@typescript-eslint/typescript-estree";
27
```
28
29
CommonJS:
30
31
```javascript
32
const { parse, parseForESLint } = require("@typescript-eslint/parser");
33
```
34
35
## Basic Usage
36
37
### ESLint Configuration
38
39
```javascript
40
// eslint.config.js or .eslintrc.js
41
module.exports = {
42
parser: "@typescript-eslint/parser",
43
parserOptions: {
44
sourceType: "module",
45
ecmaFeatures: {
46
jsx: true
47
}
48
}
49
};
50
```
51
52
### With TypeScript Project
53
54
```javascript
55
module.exports = {
56
parser: "@typescript-eslint/parser",
57
parserOptions: {
58
project: "./tsconfig.json",
59
tsconfigRootDir: __dirname,
60
sourceType: "module"
61
}
62
};
63
```
64
65
### Direct Parser Usage
66
67
```typescript
68
import { parseForESLint } from "@typescript-eslint/parser";
69
70
const code = 'const greeting: string = "Hello, TypeScript!";';
71
const result = parseForESLint(code, {
72
sourceType: "module",
73
project: "./tsconfig.json"
74
});
75
76
const { ast, services, scopeManager, visitorKeys } = result;
77
```
78
79
## Architecture
80
81
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:
82
83
- **TypeScript ESTree Integration**: Leverages `@typescript-eslint/typescript-estree` to convert TypeScript AST nodes into ESTree-compatible format that ESLint can process
84
- **Scope Analysis**: Uses `@typescript-eslint/scope-manager` to provide variable and reference tracking across TypeScript constructs
85
- **Type Information Access**: When configured with a TypeScript project, provides access to TypeScript's type checker and symbol information
86
- **Performance Optimization**: Supports both project-aware parsing (with type information) and isolated parsing (faster, without type information)
87
- **AST Mapping**: Maintains bidirectional mappings between ESTree nodes and TypeScript AST nodes for seamless integration
88
89
The parser operates in two primary modes:
90
1. **Project Mode**: Requires `tsconfig.json` and provides full type information access
91
2. **Isolated Mode**: Parses individual files without project context for better performance
92
93
## Capabilities
94
95
### Core Parsing
96
97
Main parser functions for converting TypeScript code into ESLint-compatible AST.
98
99
```typescript { .api }
100
/**
101
* Parse TypeScript/JavaScript code and return just the AST
102
* @param code - Source code string or TypeScript SourceFile
103
* @param options - Parser configuration options
104
* @returns ESLint-compatible AST
105
*/
106
function parse(
107
code: string | ts.SourceFile,
108
options?: ParserOptions
109
): ESLintProgram;
110
111
/**
112
* Main parser function that returns complete result for ESLint
113
* @param code - Source code string or TypeScript SourceFile
114
* @param parserOptions - Parser configuration options
115
* @returns Complete parser result with AST, services, scope manager, and visitor keys
116
*/
117
function parseForESLint(
118
code: string | ts.SourceFile,
119
parserOptions?: ParserOptions | null
120
): ParseForESLintResult;
121
122
interface ParseForESLintResult {
123
/** The parsed AST with ESLint-specific properties */
124
ast: ESLintProgram;
125
/** Scope analysis manager for variable and reference tracking */
126
scopeManager: ScopeManager;
127
/** Parser services for TypeScript type information access */
128
services: ParserServices;
129
/** Keys for AST traversal */
130
visitorKeys: VisitorKeys;
131
}
132
133
interface ESLintProgram extends AST<{ comment: true; tokens: true }> {
134
/** Array of comment nodes */
135
comments: TSESTree.Comment[];
136
/** Source location range */
137
range: [number, number];
138
/** Array of token nodes */
139
tokens: TSESTree.Token[];
140
}
141
```
142
143
### Cache Management
144
145
Utility function for clearing internal parser caches.
146
147
```typescript { .api }
148
/**
149
* Clears all internal parser caches used by the parser system
150
* Clears: TSConfig resolution cache, program cache, watch caches, glob cache,
151
* project service cache, and default project matched files cache
152
* Generally not needed in normal usage - intended for testing environments
153
* or custom tooling that processes many projects to prevent memory leaks
154
*/
155
function clearCaches(): void;
156
```
157
158
### TypeScript Program Creation
159
160
Utility for creating TypeScript programs from configuration files.
161
162
```typescript { .api }
163
/**
164
* Creates a TypeScript program from a TypeScript configuration file
165
* @param configFile - Path to tsconfig.json file
166
* @param projectDirectory - Optional project directory override
167
* @returns TypeScript Program instance
168
*/
169
function createProgram(
170
configFile: string,
171
projectDirectory?: string
172
): ts.Program;
173
```
174
175
### Parser Options Utilities
176
177
Utility for removing project-related options to enable faster isolated parsing.
178
179
```typescript { .api }
180
/**
181
* Removes options that prompt the parser to parse with type information
182
* Use this for faster isolated file parsing without project context
183
* @param opts - Original parser options
184
* @returns Options with project-related fields removed
185
*/
186
function withoutProjectParserOptions<Options extends object>(
187
opts: Options
188
): Omit<Options, 'EXPERIMENTAL_useProjectService' | 'project' | 'projectService'>;
189
```
190
191
### Parser Metadata
192
193
Package version and metadata constants.
194
195
```typescript { .api }
196
/** Package version string */
197
const version: string;
198
199
/** Parser metadata for ESLint */
200
const meta: {
201
name: 'typescript-eslint/parser';
202
version: string;
203
};
204
```
205
206
## Configuration Options
207
208
```typescript { .api }
209
interface ParserOptions {
210
/** Allows additional properties for extensibility */
211
[additionalProperties: string]: unknown;
212
213
/** Source code type: 'script', 'module', or 'commonjs' */
214
sourceType?: 'script' | 'module' | 'commonjs';
215
216
/** ECMAScript version support */
217
ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17
218
| 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | 2026
219
| 'latest';
220
221
/** ECMAScript feature configuration */
222
ecmaFeatures?: {
223
[key: string]: unknown;
224
/** Enable global return statements */
225
globalReturn?: boolean;
226
/** Enable JSX parsing */
227
jsx?: boolean;
228
};
229
230
/** TypeScript project configuration file path or boolean */
231
project?: boolean | string | string[] | null;
232
233
/** Root directory for TypeScript config resolution */
234
tsconfigRootDir?: string;
235
236
/** Provided TypeScript programs for parsing */
237
programs?: ts.Program[] | null;
238
239
/** Enable experimental decorators without project */
240
experimentalDecorators?: boolean;
241
242
/** Enable decorator metadata without project */
243
emitDecoratorMetadata?: boolean;
244
245
/** Enable isolated declarations mode */
246
isolatedDeclarations?: boolean;
247
248
/** Debug output configuration */
249
debugLevel?: boolean | ('eslint' | 'typescript' | 'typescript-eslint')[];
250
251
/** Allow TypeScript syntax and semantic errors */
252
errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
253
254
/** Cause parser to error on unknown AST node types */
255
errorOnUnknownASTType?: boolean;
256
257
/** Additional file extensions to parse */
258
extraFileExtensions?: string[];
259
260
/** File path for the code being parsed */
261
filePath?: string;
262
263
/** Library type definitions to include */
264
lib?: string[];
265
266
/** JSX pragma configuration */
267
jsxPragma?: string | null;
268
269
/** JSX fragment name configuration */
270
jsxFragmentName?: string | null;
271
272
/** JSDoc parsing mode configuration */
273
jsDocParsingMode?: 'all' | 'none' | 'type-info';
274
275
/** Include source ranges in AST nodes */
276
range?: boolean;
277
278
/** Include tokens in parser result */
279
tokens?: boolean;
280
281
/** Warn on unsupported TypeScript versions */
282
warnOnUnsupportedTypeScriptVersion?: boolean;
283
284
/** Project folders to ignore during project resolution */
285
projectFolderIgnoreList?: string[];
286
287
/** Project service configuration */
288
projectService?: boolean | ProjectServiceOptions;
289
290
/** Cache configuration */
291
cacheLifetime?: {
292
glob?: number | 'Infinity';
293
};
294
}
295
296
interface ProjectServiceOptions {
297
/** Files allowed with default project despite not matching */
298
allowDefaultProject?: string[];
299
300
/** Path to default TSConfig instead of TypeScript's default */
301
defaultProject?: string;
302
303
/** Whether to load TypeScript plugins from TSConfig */
304
loadTypeScriptPlugins?: boolean;
305
306
/** Maximum number of default project file matches */
307
maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING?: number;
308
}
309
```
310
311
## Parser Services
312
313
TypeScript type information services available when using project configuration.
314
315
```typescript { .api }
316
/** Union type of parser services with or without type information */
317
type ParserServices = ParserServicesWithTypeInformation | ParserServicesWithoutTypeInformation;
318
319
/** Parser services available when TypeScript project is configured */
320
interface ParserServicesWithTypeInformation {
321
/** TypeScript program instance */
322
program: ts.Program;
323
324
/** Get TypeScript symbol at ESTree node location */
325
getSymbolAtLocation: (node: TSESTree.Node) => ts.Symbol | undefined;
326
327
/** Get TypeScript type at ESTree node location */
328
getTypeAtLocation: (node: TSESTree.Node) => ts.Type;
329
330
/** Map from ESTree nodes to TypeScript nodes */
331
esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, TSNode | TSToken>;
332
333
/** Map from TypeScript nodes to ESTree nodes */
334
tsNodeToESTreeNodeMap: WeakMap<TSNode | TSToken, TSESTree.Node>;
335
336
/** Whether decorator metadata emission is enabled */
337
emitDecoratorMetadata: boolean | undefined;
338
339
/** Whether experimental decorators are enabled */
340
experimentalDecorators: boolean | undefined;
341
342
/** Whether isolated declarations mode is enabled */
343
isolatedDeclarations: boolean | undefined;
344
}
345
346
/** Parser services available when no TypeScript project is configured */
347
interface ParserServicesWithoutTypeInformation {
348
/** No TypeScript program available */
349
program: null;
350
351
/** Map from ESTree nodes to TypeScript nodes */
352
esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, TSNode | TSToken>;
353
354
/** Map from TypeScript nodes to ESTree nodes */
355
tsNodeToESTreeNodeMap: WeakMap<TSNode | TSToken, TSESTree.Node>;
356
357
/** Whether decorator metadata emission is enabled */
358
emitDecoratorMetadata: boolean | undefined;
359
360
/** Whether experimental decorators are enabled */
361
experimentalDecorators: boolean | undefined;
362
363
/** Whether isolated declarations mode is enabled */
364
isolatedDeclarations: boolean | undefined;
365
}
366
```
367
368
## Additional Types
369
370
```typescript { .api }
371
/** Scope manager for variable and reference tracking */
372
interface ScopeManager {
373
// Detailed scope analysis functionality from @typescript-eslint/scope-manager
374
}
375
376
/** Visitor keys for AST traversal */
377
interface VisitorKeys {
378
// AST traversal keys from @typescript-eslint/visitor-keys
379
}
380
381
/** TypeScript AST node types */
382
type TSNode = ts.Node;
383
384
/** TypeScript token types */
385
type TSToken = ts.Token;
386
387
/** AST type with specific options */
388
interface AST<T extends { comment: boolean; tokens: boolean }> {
389
type: string;
390
body: any[];
391
sourceType: string;
392
// Additional AST properties based on TypeScript ESTree
393
}
394
```
395
396
## Usage Examples
397
398
### Basic TypeScript Parsing
399
400
```typescript
401
import { parseForESLint } from "@typescript-eslint/parser";
402
403
const typeScriptCode = `
404
interface User {
405
name: string;
406
age: number;
407
}
408
409
const user: User = {
410
name: "Alice",
411
age: 30
412
};
413
`;
414
415
const result = parseForESLint(typeScriptCode, {
416
sourceType: "module"
417
});
418
419
console.log(result.ast.type); // "Program"
420
console.log(result.ast.body.length); // Number of top-level statements
421
```
422
423
### With Type Information
424
425
```typescript
426
import { parseForESLint } from "@typescript-eslint/parser";
427
428
const result = parseForESLint(code, {
429
sourceType: "module",
430
project: "./tsconfig.json",
431
tsconfigRootDir: __dirname
432
});
433
434
if (result.services.program) {
435
// Type information is available
436
const typeChecker = result.services.program.getTypeChecker();
437
438
// Use getTypeAtLocation and getSymbolAtLocation
439
// to access TypeScript's type information
440
}
441
```
442
443
### JSX Support
444
445
```typescript
446
import { parseForESLint } from "@typescript-eslint/parser";
447
448
const jsxCode = `
449
const Component = () => {
450
return <div>Hello, TypeScript + JSX!</div>;
451
};
452
`;
453
454
const result = parseForESLint(jsxCode, {
455
sourceType: "module",
456
ecmaFeatures: {
457
jsx: true
458
}
459
});
460
```
461
462
### Isolated Parsing for Performance
463
464
```typescript
465
import { parseForESLint, withoutProjectParserOptions } from "@typescript-eslint/parser";
466
467
const originalOptions = {
468
sourceType: "module",
469
project: "./tsconfig.json",
470
tsconfigRootDir: __dirname
471
};
472
473
// Remove project options for faster parsing
474
const isolatedOptions = withoutProjectParserOptions(originalOptions);
475
476
const result = parseForESLint(code, isolatedOptions);
477
// This will be much faster but won't have type information
478
```
479
480
## Performance Considerations
481
482
### Project vs Isolated Parsing
483
484
**Project Parsing** (with `project` option):
485
- **Pros**: Full type information access, complete semantic analysis, works with complex TypeScript features
486
- **Cons**: Slower performance, higher memory usage, requires valid `tsconfig.json`
487
- **Use Case**: Production linting where type information is needed for rules
488
489
**Isolated Parsing** (without `project` option):
490
- **Pros**: Much faster parsing, lower memory footprint, no project setup required
491
- **Cons**: No type information, limited to syntactic analysis only
492
- **Use Case**: Quick syntax checking, development tools, CI environments where speed matters
493
494
### Memory Management
495
496
- Use `clearCaches()` in long-running processes that lint many different projects
497
- Consider `withoutProjectParserOptions()` for batch processing to avoid memory buildup
498
- Project service mode (`projectService: true`) can be more memory efficient for large codebases
499
500
### Configuration Tips
501
502
```typescript
503
// For maximum performance (syntax-only)
504
const fastOptions = {
505
sourceType: "module",
506
ecmaFeatures: { jsx: true }
507
// No project option = faster parsing
508
};
509
510
// For full type information (slower but complete)
511
const completeOptions = {
512
sourceType: "module",
513
project: "./tsconfig.json",
514
tsconfigRootDir: __dirname
515
};
516
```
517
518
## Error Handling
519
520
### Common Error Scenarios
521
522
**Project Configuration Errors:**
523
```typescript
524
// Invalid tsconfig.json path
525
try {
526
const result = parseForESLint(code, {
527
project: "./invalid-tsconfig.json"
528
});
529
} catch (error) {
530
// Handle TSConfig resolution errors
531
console.error("Failed to resolve TypeScript project:", error.message);
532
}
533
```
534
535
**TypeScript Version Warnings:**
536
```typescript
537
// Suppress TypeScript version warnings
538
const result = parseForESLint(code, {
539
warnOnUnsupportedTypeScriptVersion: false
540
});
541
```
542
543
**Syntax Errors:**
544
```typescript
545
// TypeScript syntax errors in code
546
const invalidCode = "const x: = 123;"; // Invalid syntax
547
try {
548
const result = parseForESLint(invalidCode);
549
} catch (error) {
550
// Handle parsing errors
551
console.error("Parse error:", error.message);
552
}
553
```
554
555
### Error Prevention Tips
556
557
- Always validate `tsconfig.json` paths exist before using `project` option
558
- Use `errorOnTypeScriptSyntacticAndSemanticIssues: false` (default) to allow ESLint rules to handle errors
559
- Test parser options with sample files before processing large codebases
560
- Use `clearCaches()` if experiencing memory-related errors in long-running processes