Utility functions for working with TypeScript's Abstract Syntax Tree (AST) and type system
npx @tessl/cli install tessl/npm-tsutils@3.21.00
# TSUtils
1
2
TSUtils provides comprehensive utility functions and type guard functions for working with TypeScript's Abstract Syntax Tree (AST) and type system. It offers backwards compatibility with TypeScript 2.8.0+ and includes modular imports for selective usage - users can import only type guards, only utilities, or both. The library features version-specific type guard functions to maintain compatibility across different TypeScript versions, with specialized functions for traversing AST nodes, analyzing types, working with comments and tokens, and performing type-safe operations on TypeScript compiler APIs.
3
4
## Package Information
5
6
- **Package Name**: tsutils
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install tsutils`
10
- **Peer Dependencies**: `typescript >=2.8.0`
11
12
## Core Imports
13
14
```typescript
15
import * as utils from "tsutils";
16
// Access both type guards and utilities
17
utils.isIdentifier(node);
18
utils.getLineRanges(sourceFile);
19
```
20
21
For selective imports:
22
23
```typescript
24
// Only type guards
25
import { isIdentifier, isCallExpression } from "tsutils/typeguard";
26
27
// Only utilities
28
import { forEachComment, forEachToken } from "tsutils/util";
29
30
// Version-specific type guards
31
import { isIdentifier } from "tsutils/typeguard/2.8";
32
```
33
34
CommonJS:
35
36
```javascript
37
const utils = require("tsutils");
38
const { isIdentifier, forEachToken } = require("tsutils");
39
```
40
41
## Basic Usage
42
43
```typescript
44
import * as ts from "typescript";
45
import { isIdentifier, isCallExpression, forEachToken, getLineRanges } from "tsutils";
46
47
// Type guard usage
48
function analyzeNode(node: ts.Node) {
49
if (isIdentifier(node)) {
50
// node is now typed as ts.Identifier
51
console.log("Identifier:", node.text);
52
}
53
54
if (isCallExpression(node)) {
55
// node is now typed as ts.CallExpression
56
console.log("Function call:", node.expression);
57
}
58
}
59
60
// Utility usage
61
function analyzeSourceFile(sourceFile: ts.SourceFile) {
62
// Iterate through all tokens
63
forEachToken(sourceFile, (token) => {
64
console.log("Token:", ts.SyntaxKind[token.kind]);
65
});
66
67
// Get line information
68
const lines = getLineRanges(sourceFile);
69
console.log("Total lines:", lines.length);
70
}
71
```
72
73
## Architecture
74
75
TSUtils is organized into two main functional areas:
76
77
- **Type Guards**: Functions that narrow TypeScript's union types for AST nodes and type system types, with version-specific compatibility layers (2.8, 2.9, 3.0, 3.2, next)
78
- **Utilities**: General-purpose functions for AST traversal, analysis, text processing, and compiler integration
79
- **Modular Design**: Selective imports allow users to load only the functionality they need
80
- **Version Compatibility**: Hierarchical export structure ensures compatibility across TypeScript versions
81
82
## Capabilities
83
84
### Node Type Guards
85
86
Type guard functions for TypeScript AST nodes using `ts.SyntaxKind` enumeration. Provides 181 functions covering all TypeScript syntax constructs including declarations, expressions, statements, literals, and JSX elements.
87
88
```typescript { .api }
89
function isIdentifier(node: ts.Node): node is ts.Identifier;
90
function isCallExpression(node: ts.Node): node is ts.CallExpression;
91
function isIfStatement(node: ts.Node): node is ts.IfStatement;
92
function isStringLiteral(node: ts.Node): node is ts.StringLiteral;
93
function isFunctionDeclaration(node: ts.Node): node is ts.FunctionDeclaration;
94
```
95
96
[Node Type Guards](./node-typeguards.md)
97
98
### Type System Guards
99
100
Type guard functions for TypeScript's type system using `ts.TypeFlags`. Provides 18 functions for checking union types, intersection types, literal types, object types, and other type system constructs.
101
102
```typescript { .api }
103
function isUnionType(type: ts.Type): type is ts.UnionType;
104
function isIntersectionType(type: ts.Type): type is ts.IntersectionType;
105
function isLiteralType(type: ts.Type): type is ts.LiteralType;
106
function isObjectType(type: ts.Type): type is ts.ObjectType;
107
function isTypeReference(type: ts.Type): type is ts.TypeReference;
108
```
109
110
[Type System Guards](./type-guards.md)
111
112
### AST Traversal and Analysis
113
114
Comprehensive utilities for navigating, analyzing, and manipulating TypeScript AST nodes. Includes token iteration, comment processing, position mapping, and node relationship traversal.
115
116
```typescript { .api }
117
function forEachToken(node: ts.Node, cb: (node: ts.Node) => void, sourceFile?: ts.SourceFile): void;
118
function forEachComment(node: ts.Node, cb: ForEachCommentCallback, sourceFile?: ts.SourceFile): void;
119
function getPreviousToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
120
function getNextToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
121
function getAstNodeAtPosition(node: ts.Node, pos: number): ts.Node | undefined;
122
```
123
124
[AST Traversal and Analysis](./ast-traversal.md)
125
126
### Code Analysis and Utilities
127
128
Advanced analysis utilities for scope boundaries, variable declarations, control flow, import/export analysis, and compiler option checking.
129
130
```typescript { .api }
131
function isScopeBoundary(node: ts.Node): ScopeBoundary;
132
function getVariableDeclarationKind(declarationList: ts.VariableDeclarationList): VariableDeclarationKind;
133
function hasModifier(modifiers: ts.ModifiersArray | undefined, ...kinds: Array<ts.Modifier['kind']>): boolean;
134
function isParameterProperty(node: ts.ParameterDeclaration): boolean;
135
function findImports(sourceFile: ts.SourceFile, kinds: ImportKind): Array<ts.StringLiteral | ts.NoSubstitutionTemplateLiteral>;
136
```
137
138
[Code Analysis and Utilities](./code-analysis.md)
139
140
### Text Processing and Validation
141
142
Text processing utilities for source code analysis including line range calculation, identifier validation, comment extraction, and position-based operations.
143
144
```typescript { .api }
145
function getLineRanges(sourceFile: ts.SourceFile): LineRange[];
146
function isValidIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
147
function commentText(sourceText: string, comment: ts.CommentRange): string;
148
function isPositionInComment(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): boolean;
149
function isSameLine(sourceFile: ts.SourceFile, pos1: number, pos2: number): boolean;
150
```
151
152
[Text Processing and Validation](./text-processing.md)
153
154
### Variable Usage Analysis
155
156
Specialized utilities for analyzing variable declarations, usage patterns, and scope analysis. Provides detailed information about variable domains, export status, and usage locations.
157
158
```typescript { .api }
159
function collectVariableUsage(sourceFile: ts.SourceFile): Map<ts.Identifier, VariableInfo>;
160
function getUsageDomain(node: ts.Identifier): UsageDomain | undefined;
161
function getDeclarationDomain(node: ts.Identifier): DeclarationDomain | undefined;
162
163
interface VariableInfo {
164
domain: DeclarationDomain;
165
exported: boolean;
166
uses: VariableUse[];
167
inGlobalScope: boolean;
168
declarations: ts.Identifier[];
169
}
170
```
171
172
[Variable Usage Analysis](./variable-usage.md)
173
174
### Type System Utilities
175
176
Advanced type system analysis including type assignability checking, property analysis, class type inspection, and type manipulation utilities.
177
178
```typescript { .api }
179
function isTypeAssignableToNumber(checker: ts.TypeChecker, type: ts.Type): boolean;
180
function isTypeAssignableToString(checker: ts.TypeChecker, type: ts.Type): boolean;
181
function unionTypeParts(type: ts.Type): ts.Type[];
182
function getPropertyOfType(type: ts.Type, name: ts.__String): ts.Symbol | undefined;
183
function getSymbolOfClassLikeDeclaration(node: ts.ClassLikeDeclaration, checker: ts.TypeChecker): ts.Symbol;
184
```
185
186
[Type System Utilities](./type-utilities.md)
187
188
### Control Flow Analysis
189
190
Control flow analysis utilities for determining statement reachability, analyzing function signatures, and identifying control flow termination points.
191
192
```typescript { .api }
193
function endsControlFlow(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): boolean;
194
function getControlFlowEnd(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): ControlFlowEnd;
195
function callExpressionAffectsControlFlow(node: ts.CallExpression, checker: ts.TypeChecker): SignatureEffect | undefined;
196
```
197
198
[Control Flow Analysis](./control-flow.md)
199
200
## Types
201
202
### Common Enums
203
204
```typescript { .api }
205
enum VariableDeclarationKind {
206
Var,
207
Let,
208
Const
209
}
210
211
enum ScopeBoundary {
212
None = 0,
213
Function = 1,
214
Block = 2,
215
Type = 4,
216
ConditionalType = 8
217
}
218
219
enum AccessKind {
220
None = 0,
221
Read = 1,
222
Write = 2,
223
Delete = 4,
224
ReadWrite = Read | Write,
225
Modification = Write | Delete
226
}
227
228
enum DeclarationDomain {
229
Namespace = 1,
230
Type = 2,
231
Value = 4,
232
Import = 8,
233
Any = Namespace | Type | Value
234
}
235
236
enum UsageDomain {
237
Namespace = 1,
238
Type = 2,
239
Value = 4,
240
ValueOrNamespace = Value | Namespace,
241
Any = Namespace | Type | Value,
242
TypeQuery = 8
243
}
244
```
245
246
### Callback Types
247
248
```typescript { .api }
249
type ForEachTokenCallback = (fullText: string, kind: ts.SyntaxKind, range: ts.TextRange, parent: ts.Node) => void;
250
type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void;
251
```
252
253
### Utility Interfaces
254
255
```typescript { .api }
256
interface LineRange extends ts.TextRange {
257
contentLength: number;
258
}
259
260
interface NodeWrap {
261
node: ts.Node;
262
kind: ts.SyntaxKind;
263
children: NodeWrap[];
264
next?: NodeWrap;
265
skip?: NodeWrap;
266
parent?: NodeWrap;
267
}
268
```