Utilities for working with TypeScript + ESLint together
npx @tessl/cli install tessl/npm-typescript-eslint--utils@8.42.00
# @typescript-eslint/utils
1
2
Comprehensive utilities for working with TypeScript and ESLint together. This package provides a complete toolkit for developing ESLint rules with TypeScript support, including AST manipulation utilities, rule creation helpers, JSON Schema types, and TypeScript-specific utilities.
3
4
## Package Information
5
6
- **Package Name**: @typescript-eslint/utils
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @typescript-eslint/utils`
10
11
## Core Imports
12
13
```typescript
14
// Main namespace imports
15
import { ASTUtils, ESLintUtils, JSONSchema, TSESLint, TSUtils } from '@typescript-eslint/utils';
16
17
// Individual namespace imports
18
import { ASTUtils } from '@typescript-eslint/utils';
19
import { ESLintUtils } from '@typescript-eslint/utils';
20
import { JSONSchema } from '@typescript-eslint/utils';
21
import { TSESLint } from '@typescript-eslint/utils';
22
import { TSUtils } from '@typescript-eslint/utils';
23
24
// Re-exported types from dependencies
25
import { AST_NODE_TYPES, AST_TOKEN_TYPES, TSESTree } from '@typescript-eslint/utils';
26
import type { ParserServices, ParserServicesWithTypeInformation } from '@typescript-eslint/utils';
27
```
28
29
Alternative subpath imports:
30
31
```typescript
32
// Import from specific subpaths (as defined in package.json exports)
33
import * as ASTUtils from '@typescript-eslint/utils/ast-utils';
34
import * as ESLintUtils from '@typescript-eslint/utils/eslint-utils';
35
import * as JSONSchema from '@typescript-eslint/utils/json-schema';
36
import * as TSESLint from '@typescript-eslint/utils/ts-eslint';
37
```
38
39
## Basic Usage
40
41
### Creating an ESLint Rule
42
43
```typescript { .api }
44
import { ESLintUtils } from '@typescript-eslint/utils';
45
46
// Create a rule creator with documentation URL generator
47
const createRule = ESLintUtils.RuleCreator(
48
name => `https://example.com/rules/${name}`
49
);
50
51
// Define and export a rule
52
export default createRule({
53
name: 'my-custom-rule',
54
meta: {
55
type: 'problem',
56
docs: {
57
description: 'My custom TypeScript ESLint rule',
58
},
59
messages: {
60
error: 'This is not allowed: {{details}}',
61
},
62
schema: [
63
{
64
type: 'object',
65
properties: {
66
checkStrings: { type: 'boolean' }
67
},
68
additionalProperties: false,
69
}
70
],
71
},
72
defaultOptions: [{ checkStrings: true }],
73
create(context) {
74
return {
75
CallExpression(node) {
76
context.report({
77
node,
78
messageId: 'error',
79
data: { details: 'function calls' }
80
});
81
}
82
};
83
},
84
});
85
```
86
87
### Using AST Utilities
88
89
```typescript { .api }
90
import { ASTUtils } from '@typescript-eslint/utils';
91
92
// In a rule implementation
93
create(context) {
94
return {
95
CallExpression(node) {
96
// Check for optional call expressions
97
if (ASTUtils.isOptionalCallExpression(node)) {
98
// Handle optional chaining calls like obj?.method()
99
}
100
101
// Check if node is a function
102
if (ASTUtils.isFunction(node.callee)) {
103
// Handle direct function calls
104
}
105
},
106
107
MemberExpression(node) {
108
// Check for type assertions
109
if (ASTUtils.isTypeAssertion(node.object)) {
110
// Handle type assertions like (obj as Type).prop
111
}
112
}
113
};
114
}
115
```
116
117
### Accessing Type Information
118
119
```typescript { .api }
120
import { ESLintUtils } from '@typescript-eslint/utils';
121
122
// In a rule that needs type information
123
create(context) {
124
// Get parser services for type-aware linting
125
const services = ESLintUtils.getParserServices(context);
126
const checker = services.program.getTypeChecker();
127
128
return {
129
Identifier(node) {
130
// Convert ESTree node to TypeScript node
131
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
132
133
// Get type information
134
const type = checker.getTypeAtLocation(tsNode);
135
const typeString = checker.typeToString(type);
136
137
if (typeString === 'string') {
138
// Handle string types specifically
139
}
140
}
141
};
142
}
143
```
144
145
## Architecture Overview
146
147
The package is organized into five main namespaces, each serving specific aspects of TypeScript ESLint development:
148
149
### ASTUtils Namespace
150
Provides comprehensive utilities for Abstract Syntax Tree manipulation and analysis:
151
- **Node type predicates**: Check for specific AST node types (functions, identifiers, expressions)
152
- **Token predicates**: Validate token types (punctuators, keywords, operators)
153
- **Helper functions**: Node type guards and conditional type checking
154
- **ESLint utilities**: Integration helpers for ESLint-specific AST operations
155
156
### ESLintUtils Namespace
157
Contains rule creation and ESLint integration utilities:
158
- **Rule creation**: `RuleCreator` for generating well-documented rules
159
- **Parser services**: Access TypeScript compiler API within rules
160
- **Option handling**: Default option application and deep merging
161
- **Type inference**: Extract types from rule definitions
162
163
### JSONSchema Namespace
164
Provides complete JSON Schema v4 types for rule configuration:
165
- **Schema types**: All JSON Schema primitive and complex types
166
- **Validation schemas**: Object, array, string, number schema definitions
167
- **Composition schemas**: AllOf, AnyOf, OneOf schema combinations
168
- **Reference handling**: Schema references and reusable definitions
169
170
### TSESLint Namespace
171
Offers TypeScript-enhanced ESLint types and classes:
172
- **Configuration**: Both legacy and flat config types
173
- **Rules**: Enhanced rule interfaces with TypeScript support
174
- **Linting**: ESLint and Linter classes with TypeScript integration
175
- **Scope analysis**: Variable and reference tracking
176
- **Source code**: Enhanced source code representation
177
178
### TSUtils Namespace
179
Provides TypeScript-specific utility functions:
180
- **Type guards**: Runtime type checking utilities
181
- **Type manipulation**: Utility types for TypeScript development
182
- **Array handling**: Type-safe array operations
183
184
## Key Capabilities
185
186
### Rule Development
187
188
Create sophisticated ESLint rules with full TypeScript support:
189
190
```typescript { .api }
191
import { ESLintUtils, ASTUtils, TSESLint } from '@typescript-eslint/utils';
192
193
const createRule = ESLintUtils.RuleCreator(name => `https://docs.example.com/${name}`);
194
195
type Options = [{
196
allowOptional?: boolean;
197
ignoreArrays?: boolean;
198
}];
199
200
type MessageIds = 'noUnsafeCall' | 'preferOptional';
201
202
export default createRule<Options, MessageIds>({
203
name: 'safe-member-access',
204
meta: {
205
type: 'problem',
206
docs: {
207
description: 'Enforce safe member access patterns',
208
},
209
messages: {
210
noUnsafeCall: 'Unsafe member access detected',
211
preferOptional: 'Consider using optional chaining: {{suggestion}}'
212
},
213
schema: [{
214
type: 'object',
215
properties: {
216
allowOptional: { type: 'boolean' },
217
ignoreArrays: { type: 'boolean' }
218
},
219
additionalProperties: false
220
}]
221
},
222
defaultOptions: [{ allowOptional: true, ignoreArrays: false }],
223
create(context, [options]) {
224
const services = ESLintUtils.getParserServices(context);
225
226
return {
227
MemberExpression(node) {
228
// Use type information and AST utilities together
229
if (!options.allowOptional && ASTUtils.isOptionalCallExpression(node)) {
230
context.report({
231
node,
232
messageId: 'preferOptional',
233
data: { suggestion: 'obj?.method()' }
234
});
235
}
236
}
237
};
238
}
239
});
240
```
241
242
[→ See complete ESLint utilities documentation](./eslint-utils.md)
243
244
### AST Analysis and Manipulation
245
246
Comprehensive AST utilities for analyzing TypeScript code structures:
247
248
```typescript { .api }
249
import { ASTUtils, TSESTree } from '@typescript-eslint/utils';
250
251
// Node type checking
252
const isFunction = ASTUtils.isFunction(node);
253
const isOptionalCall = ASTUtils.isOptionalCallExpression(node);
254
const isTypeAssertion = ASTUtils.isTypeAssertion(node);
255
256
// Token analysis
257
const isArrow = ASTUtils.isArrowToken(token);
258
const isComma = ASTUtils.isCommaToken(token);
259
const isSemicolon = ASTUtils.isSemicolonToken(token);
260
261
// Advanced type checking with conditions
262
const isSpecificFunction = ASTUtils.isNodeOfTypeWithConditions(
263
AST_NODE_TYPES.FunctionDeclaration,
264
{ async: true }
265
);
266
```
267
268
[→ See complete AST utilities documentation](./ast-utils.md)
269
270
### Type-Safe Configuration
271
272
Define rule schemas with complete type safety using JSON Schema:
273
274
```typescript { .api }
275
import { JSONSchema } from '@typescript-eslint/utils';
276
277
// Complete rule schema definition
278
const ruleSchema: JSONSchema.JSONSchema4 = {
279
type: 'object',
280
properties: {
281
mode: {
282
type: 'string',
283
enum: ['strict', 'loose', 'disabled']
284
},
285
exceptions: {
286
type: 'array',
287
items: { type: 'string' },
288
minItems: 0
289
},
290
config: {
291
type: 'object',
292
properties: {
293
checkReturnTypes: { type: 'boolean' },
294
allowAny: { type: 'boolean' }
295
},
296
additionalProperties: false
297
}
298
},
299
additionalProperties: false,
300
required: ['mode']
301
};
302
```
303
304
[→ See complete JSON Schema documentation](./json-schema.md)
305
306
### Enhanced ESLint Integration
307
308
Access all ESLint functionality with TypeScript enhancements:
309
310
```typescript { .api }
311
import { TSESLint } from '@typescript-eslint/utils';
312
313
// Type-aware rule context
314
function createRule(context: TSESLint.RuleContext<MessageIds, Options>) {
315
// Enhanced source code access
316
const sourceCode = context.getSourceCode();
317
const tokens = sourceCode.getTokens(node);
318
319
// Scope analysis
320
const scope = context.getScope();
321
const variables = scope.variables;
322
323
// Type-safe reporting
324
context.report({
325
node,
326
messageId: 'error' as const,
327
data: { name: 'example' },
328
fix: (fixer) => fixer.replaceText(node, 'replacement')
329
});
330
}
331
```
332
333
[→ See complete TSESLint documentation](./ts-eslint.md)
334
335
### TypeScript Utilities
336
337
Additional TypeScript-specific utilities for enhanced development:
338
339
```typescript { .api }
340
import { TSUtils } from '@typescript-eslint/utils';
341
342
// Type-safe array checking
343
if (TSUtils.isArray(value)) {
344
// value is now typed as readonly unknown[]
345
value.forEach(item => {
346
// Safe array iteration
347
});
348
}
349
350
// Prevent type inference when needed
351
function example<T>(value: TSUtils.NoInfer<T>) {
352
// T will not be inferred from value parameter
353
}
354
```
355
356
[→ See complete TypeScript utilities documentation](./ts-utils.md)
357
358
### AST Types and Parser Services
359
360
Re-exported core TypeScript AST types and parser services for convenient access:
361
362
```typescript { .api }
363
// AST Node types enumeration
364
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
365
366
// AST Token types enumeration
367
import { AST_TOKEN_TYPES } from '@typescript-eslint/utils';
368
369
// TypeScript ESTree types
370
import { TSESTree } from '@typescript-eslint/utils';
371
372
// Parser service types for TypeScript integration
373
import type {
374
ParserServices,
375
ParserServicesWithTypeInformation,
376
ParserServicesWithoutTypeInformation
377
} from '@typescript-eslint/utils';
378
```
379
380
These are convenience re-exports from `@typescript-eslint/types` and `@typescript-eslint/typescript-estree` packages, eliminating the need to install and import from multiple packages.
381
382
**Usage Example:**
383
384
```typescript
385
import { AST_NODE_TYPES, TSESTree, ESLintUtils } from '@typescript-eslint/utils';
386
387
const createRule = ESLintUtils.RuleCreator(name => `https://example.com/${name}`);
388
389
export default createRule({
390
name: 'example-rule',
391
meta: {
392
type: 'problem',
393
docs: { description: 'Example rule using AST types' },
394
messages: { error: 'Error found in {{nodeType}}' },
395
schema: []
396
},
397
defaultOptions: [],
398
create(context) {
399
return {
400
[AST_NODE_TYPES.CallExpression](node: TSESTree.CallExpression) {
401
context.report({
402
node,
403
messageId: 'error',
404
data: { nodeType: node.type }
405
});
406
}
407
};
408
}
409
});
410
```
411
412
## Documentation Structure
413
414
This Knowledge Tile is organized into focused documents covering each major functional area:
415
416
- **[AST Utilities](./ast-utils.md)** - Node predicates, token analysis, and AST manipulation helpers
417
- **[ESLint Utilities](./eslint-utils.md)** - Rule creation, parser services, and ESLint integration
418
- **[JSON Schema](./json-schema.md)** - Complete JSON Schema v4 types for rule configuration
419
- **[TSESLint Types](./ts-eslint.md)** - TypeScript-enhanced ESLint classes and interfaces
420
- **[TypeScript Utils](./ts-utils.md)** - TypeScript-specific utility functions and types
421
422
Each document provides comprehensive API coverage with practical examples, enabling effective TypeScript ESLint rule development without requiring access to source code.