0
# TypeScript Scope Manager
1
2
The TypeScript Scope Manager is a TypeScript-aware scope analyser for ESLint that provides comprehensive scope analysis capabilities for JavaScript and TypeScript code. It extends ESLint's scope analysis framework to handle TypeScript-specific language features like type parameters, interfaces, enums, namespaces, and advanced type constructs.
3
4
## Package Information
5
6
- **Package Name**: @typescript-eslint/scope-manager
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @typescript-eslint/scope-manager`
10
11
## Core Imports
12
13
```typescript
14
import {
15
analyze,
16
ScopeManager,
17
AnalyzeOptions
18
} from "@typescript-eslint/scope-manager";
19
```
20
21
For additional types and classes:
22
23
```typescript
24
import {
25
Reference,
26
PatternVisitor,
27
Visitor,
28
ScopeType,
29
ReferenceFlag,
30
DefinitionType,
31
type PatternVisitorCallback,
32
type PatternVisitorOptions
33
} from "@typescript-eslint/scope-manager";
34
```
35
36
For CommonJS:
37
38
```javascript
39
const { analyze, ScopeManager, Reference, ScopeType } = require("@typescript-eslint/scope-manager");
40
```
41
42
## Basic Usage
43
44
```typescript
45
import { analyze } from "@typescript-eslint/scope-manager";
46
import type { TSESTree } from "@typescript-eslint/types";
47
import { parse } from "@typescript-eslint/parser";
48
49
// Parse TypeScript code to get AST
50
const code = `
51
function greet(name: string): string {
52
const message = 'Hello, ' + name;
53
return message;
54
}
55
`;
56
57
const ast = parse(code, {
58
loc: true,
59
range: true,
60
}) as TSESTree.Program;
61
62
// Analyze scope
63
const scopeManager = analyze(ast, {
64
globalReturn: false,
65
impliedStrict: false,
66
jsxPragma: 'React',
67
lib: ['esnext'],
68
sourceType: 'module'
69
});
70
71
// Access global scope
72
console.log(scopeManager.globalScope);
73
74
// Get all scopes
75
console.log(scopeManager.scopes);
76
77
// Get variables in each scope
78
scopeManager.scopes.forEach(scope => {
79
console.log(`Scope type: ${scope.type}`);
80
console.log(`Variables: ${scope.variables.map(v => v.name)}`);
81
});
82
```
83
84
## Architecture
85
86
The TypeScript Scope Manager is built around several key components:
87
88
- **Scope Analysis**: `analyze()` function that processes AST nodes and creates scope trees
89
- **Scope Management**: `ScopeManager` class that maintains scope hierarchies and variable mappings
90
- **Scope Types**: Comprehensive set of scope classes for different language constructs
91
- **Variable System**: Variable and reference tracking with TypeScript type context awareness
92
- **Definition System**: Detailed tracking of where variables are defined and how they're used
93
- **Reference System**: Complete reference tracking with read/write analysis
94
95
## Capabilities
96
97
### Core Analysis
98
99
Main entry point for analyzing AST nodes and generating comprehensive scope information with TypeScript awareness.
100
101
```typescript { .api }
102
function analyze(
103
tree: TSESTree.Node,
104
options?: AnalyzeOptions
105
): ScopeManager;
106
107
interface AnalyzeOptions {
108
childVisitorKeys?: Record<string, string[]>;
109
globalReturn?: boolean;
110
impliedStrict?: boolean;
111
jsxPragma?: string | null;
112
jsxFragmentName?: string | null;
113
lib?: Lib[];
114
sourceType?: SourceType;
115
/** @deprecated This option never did what it was intended for and will be removed in a future major release. */
116
emitDecoratorMetadata?: boolean;
117
}
118
```
119
120
[Core Analysis](./analysis.md)
121
122
### Scope Management
123
124
Central scope management system that maintains scope hierarchies, variable mappings, and provides scope navigation and querying capabilities.
125
126
```typescript { .api }
127
class ScopeManager {
128
currentScope: Scope | null;
129
declaredVariables: WeakMap<TSESTree.Node, Variable[]>;
130
globalScope: GlobalScope | null;
131
nodeToScope: WeakMap<TSESTree.Node, Scope[]>;
132
scopes: Scope[];
133
get variables(): Variable[];
134
135
getDeclaredVariables(node: TSESTree.Node): Variable[];
136
acquire(node: TSESTree.Node, inner?: boolean): Scope | null;
137
isES6(): boolean;
138
isGlobalReturn(): boolean;
139
isImpliedStrict(): boolean;
140
isModule(): boolean;
141
isStrictModeSupported(): boolean;
142
}
143
```
144
145
[Scope Management](./scope-management.md)
146
147
### Scope Types
148
149
Comprehensive scope type system covering all JavaScript and TypeScript language constructs with specialized behavior for each scope type.
150
151
```typescript { .api }
152
type Scope = BlockScope | CatchScope | ClassScope | ClassFieldInitializerScope
153
| ClassStaticBlockScope | ConditionalTypeScope | ForScope | FunctionScope
154
| FunctionExpressionNameScope | FunctionTypeScope | GlobalScope | MappedTypeScope
155
| ModuleScope | SwitchScope | TSEnumScope | TSModuleScope | TypeScope | WithScope;
156
157
enum ScopeType {
158
block = "block",
159
catch = "catch",
160
class = "class",
161
classFieldInitializer = "class-field-initializer",
162
classStaticBlock = "class-static-block",
163
conditionalType = "conditionalType",
164
for = "for",
165
function = "function",
166
functionExpressionName = "function-expression-name",
167
functionType = "functionType",
168
global = "global",
169
mappedType = "mappedType",
170
module = "module",
171
switch = "switch",
172
tsEnum = "tsEnum",
173
tsModule = "tsModule",
174
type = "type",
175
with = "with"
176
}
177
```
178
179
[Scope Types](./scope-types.md)
180
181
### Variable System
182
183
Variable tracking system with TypeScript-aware type context analysis and comprehensive definition tracking.
184
185
```typescript { .api }
186
class Variable {
187
readonly name: string;
188
readonly defs: Definition[];
189
readonly identifiers: TSESTree.Identifier[];
190
readonly references: Reference[];
191
readonly scope: Scope;
192
193
get isTypeVariable(): boolean;
194
get isValueVariable(): boolean;
195
}
196
197
type ScopeVariable = ESLintScopeVariable | Variable;
198
```
199
200
[Variable System](./variable-system.md)
201
202
### Reference System
203
204
Comprehensive reference tracking system that identifies all identifier occurrences and their usage patterns.
205
206
```typescript { .api }
207
class Reference {
208
readonly from: Scope;
209
readonly identifier: TSESTree.Identifier;
210
readonly resolved: Variable | null;
211
readonly writeExpr: TSESTree.Node | null;
212
213
isWrite(): boolean;
214
isRead(): boolean;
215
isReadOnly(): boolean;
216
isWriteOnly(): boolean;
217
isReadWrite(): boolean;
218
}
219
220
enum ReferenceFlag {
221
Read = 0x1,
222
Write = 0x2,
223
ReadWrite = 0x3
224
}
225
```
226
227
[Reference System](./reference-system.md)
228
229
### Definition System
230
231
Definition tracking system that categorizes how variables are defined and provides detailed context about their declarations.
232
233
```typescript { .api }
234
type Definition = CatchClauseDefinition | ClassNameDefinition
235
| FunctionNameDefinition | ImplicitGlobalVariableDefinition | ImportBindingDefinition
236
| ParameterDefinition | TSEnumMemberDefinition | TSEnumNameDefinition
237
| TSModuleNameDefinition | TypeDefinition | VariableDefinition;
238
239
enum DefinitionType {
240
CatchClause = "CatchClause",
241
ClassName = "ClassName",
242
FunctionName = "FunctionName",
243
ImplicitGlobalVariable = "ImplicitGlobalVariable",
244
ImportBinding = "ImportBinding",
245
Parameter = "Parameter",
246
TSEnumMember = "TSEnumMemberName",
247
TSEnumName = "TSEnumName",
248
TSModuleName = "TSModuleName",
249
Type = "Type",
250
Variable = "Variable"
251
}
252
```
253
254
[Definition System](./definition-system.md)
255
256
## Common Types
257
258
```typescript { .api }
259
import type { TSESTree, SourceType, Lib } from "@typescript-eslint/types";
260
261
interface PatternVisitorOptions {
262
childVisitorKeys?: Record<string, string[]>;
263
}
264
265
type PatternVisitorCallback = (
266
pattern: TSESTree.Identifier,
267
info: {
268
assignments: (TSESTree.AssignmentExpression | TSESTree.AssignmentPattern)[];
269
rest: boolean;
270
topLevel: boolean;
271
}
272
) => void;
273
```