0
# AST Nodes
1
2
Complete set of AST node classes providing navigation, analysis, and manipulation capabilities for all TypeScript language constructs. Each node represents a specific element in the TypeScript Abstract Syntax Tree.
3
4
## Capabilities
5
6
### Base Node Class
7
8
The foundational class from which all AST nodes inherit, providing core navigation and manipulation functionality.
9
10
```typescript { .api }
11
/**
12
* Base class for all AST nodes
13
*/
14
abstract class Node<T = ts.Node> {
15
/** Get the syntax kind of this node */
16
getKind(): SyntaxKind;
17
18
/** Get the name of the syntax kind */
19
getKindName(): string;
20
21
/** Get the text of this node */
22
getText(): string;
23
24
/** Get the full text including leading trivia */
25
getFullText(): string;
26
27
/** Get the start position */
28
getStart(includeJsDocComments?: boolean): number;
29
30
/** Get the end position */
31
getEnd(): number;
32
33
/** Get the full start position including trivia */
34
getFullStart(): number;
35
36
/** Get the width of this node */
37
getWidth(includeJsDocComments?: boolean): number;
38
39
/** Get the full width including trivia */
40
getFullWidth(): number;
41
42
/** Get the parent node */
43
getParent(): Node | undefined;
44
45
/** Get the parent node, throwing if not found */
46
getParentOrThrow(): Node;
47
48
/** Get all child nodes */
49
getChildren(): Node[];
50
51
/** Get the first child node */
52
getFirstChild(): Node | undefined;
53
54
/** Get the first child node with optional condition */
55
getFirstChild<T extends Node>(condition: (node: Node) => node is T): T | undefined;
56
57
/** Get the first child node, throwing if not found */
58
getFirstChildOrThrow(): Node;
59
60
/** Get the last child node */
61
getLastChild(): Node | undefined;
62
63
/** Get the last child node with optional condition */
64
getLastChild<T extends Node>(condition: (node: Node) => node is T): T | undefined;
65
66
/** Get the last child node, throwing if not found */
67
getLastChildOrThrow(): Node;
68
69
/** Get the previous sibling */
70
getPreviousSibling(): Node | undefined;
71
72
/** Get the previous sibling with optional condition */
73
getPreviousSibling<T extends Node>(condition: (node: Node) => node is T): T | undefined;
74
75
/** Get the next sibling */
76
getNextSibling(): Node | undefined;
77
78
/** Get the next sibling with optional condition */
79
getNextSibling<T extends Node>(condition: (node: Node) => node is T): T | undefined;
80
81
/** Get all previous siblings */
82
getPreviousSiblings(): Node[];
83
84
/** Get all next siblings */
85
getNextSiblings(): Node[];
86
87
/** Get the source file this node belongs to */
88
getSourceFile(): SourceFile;
89
90
/** Get the project this node belongs to */
91
getProject(): Project;
92
93
/** Get ancestors of this node */
94
getAncestors(): Node[];
95
96
/** Get descendants of this node */
97
getDescendants(): Node[];
98
99
/** Get the first descendant matching condition */
100
getFirstDescendant<T extends Node>(condition?: (node: Node) => node is T): T | undefined;
101
102
/** Get the first descendant matching condition, throwing if not found */
103
getFirstDescendantOrThrow<T extends Node>(condition?: (node: Node) => node is T): T;
104
105
/** Check if this node is of a specific kind */
106
isKind<TKind extends SyntaxKind>(kind: TKind): this is KindToNodeMappings[TKind];
107
108
/** Cast this node to a specific kind */
109
asKind<TKind extends SyntaxKind>(kind: TKind): KindToNodeMappings[TKind] | undefined;
110
111
/** Cast this node to a specific kind, throwing if not that kind */
112
asKindOrThrow<TKind extends SyntaxKind>(kind: TKind): KindToNodeMappings[TKind];
113
114
/** Get the symbol associated with this node */
115
getSymbol(): Symbol | undefined;
116
117
/** Get the symbol associated with this node, throwing if not found */
118
getSymbolOrThrow(): Symbol;
119
120
/** Get the type associated with this node */
121
getType(): Type;
122
123
/** Forget this node and release it from cache */
124
forget(): void;
125
126
/** Forget all descendant nodes */
127
forgetDescendants(): void;
128
129
/** Check if this node was forgotten */
130
wasForgotten(): boolean;
131
132
/** Print this node to a string */
133
print(options?: PrintNodeOptions): string;
134
135
/** Remove this node */
136
remove(): void;
137
138
/** Replace this node with text */
139
replaceWithText(text: string): Node;
140
141
/** Iterate over each child */
142
forEachChild<T>(cbNode: (node: Node) => T | undefined): T | undefined;
143
144
/** Iterate over each descendant */
145
forEachDescendant<T>(cbNode: (node: Node) => T | undefined): T | undefined;
146
}
147
```
148
149
### Source File
150
151
The root node representing a TypeScript/JavaScript source file.
152
153
```typescript { .api }
154
class SourceFile extends Node {
155
/** Get the file path */
156
getFilePath(): string;
157
158
/** Get the base name of the file */
159
getBaseName(): string;
160
161
/** Get the directory name */
162
getDirName(): string;
163
164
/** Get the extension */
165
getExtension(): string;
166
167
/** Check if file was saved */
168
isSaved(): boolean;
169
170
/** Save the source file */
171
save(): Promise<void>;
172
173
/** Save the source file synchronously */
174
saveSync(): void;
175
176
/** Copy the source file to a new location */
177
copy(filePath: string, options?: SourceFileCopyOptions): SourceFile;
178
179
/** Move the source file to a new location */
180
move(filePath: string, options?: SourceFileMoveOptions): SourceFile;
181
182
/** Delete the source file */
183
delete(): Promise<void>;
184
185
/** Delete the source file synchronously */
186
deleteSync(): void;
187
188
/** Get all import declarations */
189
getImportDeclarations(): ImportDeclaration[];
190
191
/** Add an import declaration */
192
addImportDeclaration(structure: ImportDeclarationStructure): ImportDeclaration;
193
194
/** Get all export declarations */
195
getExportDeclarations(): ExportDeclaration[];
196
197
/** Add an export declaration */
198
addExportDeclaration(structure: ExportDeclarationStructure): ExportDeclaration;
199
200
/** Get all class declarations */
201
getClasses(): ClassDeclaration[];
202
203
/** Get a class by name */
204
getClass(name: string): ClassDeclaration | undefined;
205
206
/** Add a class */
207
addClass(structure: ClassDeclarationStructure): ClassDeclaration;
208
209
/** Get all function declarations */
210
getFunctions(): FunctionDeclaration[];
211
212
/** Get a function by name */
213
getFunction(name: string): FunctionDeclaration | undefined;
214
215
/** Add a function */
216
addFunction(structure: FunctionDeclarationStructure): FunctionDeclaration;
217
218
/** Get all interface declarations */
219
getInterfaces(): InterfaceDeclaration[];
220
221
/** Get an interface by name */
222
getInterface(name: string): InterfaceDeclaration | undefined;
223
224
/** Add an interface */
225
addInterface(structure: InterfaceDeclarationStructure): InterfaceDeclaration;
226
227
/** Get all enum declarations */
228
getEnums(): EnumDeclaration[];
229
230
/** Add an enum */
231
addEnum(structure: EnumDeclarationStructure): EnumDeclaration;
232
233
/** Get all type alias declarations */
234
getTypeAliases(): TypeAliasDeclaration[];
235
236
/** Add a type alias */
237
addTypeAlias(structure: TypeAliasDeclarationStructure): TypeAliasDeclaration;
238
239
/** Get all variable statements */
240
getVariableStatements(): VariableStatement[];
241
242
/** Add a variable statement */
243
addVariableStatement(structure: VariableStatementStructure): VariableStatement;
244
245
/** Organize imports */
246
organizeImports(): void;
247
248
/** Fix unused identifiers */
249
fixUnusedIdentifiers(): void;
250
}
251
```
252
253
### Class Declaration
254
255
Represents a TypeScript class declaration.
256
257
```typescript { .api }
258
class ClassDeclaration extends Node {
259
/** Get the class name */
260
getName(): string | undefined;
261
262
/** Set the class name */
263
setName(name: string): this;
264
265
/** Get the extends clause */
266
getExtends(): ExpressionWithTypeArguments | undefined;
267
268
/** Set the extends clause */
269
setExtends(text: string): this;
270
271
/** Get implemented interfaces */
272
getImplements(): ExpressionWithTypeArguments[];
273
274
/** Add an implements clause */
275
addImplements(text: string): ExpressionWithTypeArguments;
276
277
/** Get all constructors */
278
getConstructors(): ConstructorDeclaration[];
279
280
/** Add a constructor */
281
addConstructor(structure?: ConstructorDeclarationStructure): ConstructorDeclaration;
282
283
/** Get all properties */
284
getProperties(): PropertyDeclaration[];
285
286
/** Get a property by name */
287
getProperty(name: string): PropertyDeclaration | undefined;
288
289
/** Add a property */
290
addProperty(structure: PropertyDeclarationStructure): PropertyDeclaration;
291
292
/** Get all methods */
293
getMethods(): MethodDeclaration[];
294
295
/** Get a method by name */
296
getMethod(name: string): MethodDeclaration | undefined;
297
298
/** Add a method */
299
addMethod(structure: MethodDeclarationStructure): MethodDeclaration;
300
301
/** Get all getters */
302
getGetAccessors(): GetAccessorDeclaration[];
303
304
/** Add a getter */
305
addGetAccessor(structure: GetAccessorDeclarationStructure): GetAccessorDeclaration;
306
307
/** Get all setters */
308
getSetAccessors(): SetAccessorDeclaration[];
309
310
/** Add a setter */
311
addSetAccessor(structure: SetAccessorDeclarationStructure): SetAccessorDeclaration;
312
313
/** Check if class is abstract */
314
isAbstract(): boolean;
315
316
/** Set abstract modifier */
317
setIsAbstract(value: boolean): this;
318
319
/** Check if class is exported */
320
isExported(): boolean;
321
322
/** Set exported */
323
setIsExported(value: boolean): this;
324
325
/** Check if class is default export */
326
isDefaultExport(): boolean;
327
328
/** Set as default export */
329
setIsDefaultExport(value: boolean): this;
330
}
331
```
332
333
### Function Declaration
334
335
Represents a function declaration.
336
337
```typescript { .api }
338
class FunctionDeclaration extends Node {
339
/** Get the function name */
340
getName(): string | undefined;
341
342
/** Set the function name */
343
setName(name: string): this;
344
345
/** Get all parameters */
346
getParameters(): ParameterDeclaration[];
347
348
/** Add a parameter */
349
addParameter(structure: ParameterDeclarationStructure): ParameterDeclaration;
350
351
/** Get the return type node */
352
getReturnTypeNode(): TypeNode | undefined;
353
354
/** Set the return type */
355
setReturnType(type: string): this;
356
357
/** Get the function body */
358
getBody(): Block | undefined;
359
360
/** Set the function body */
361
setBodyText(text: string): this;
362
363
/** Check if function is async */
364
isAsync(): boolean;
365
366
/** Set async modifier */
367
setIsAsync(value: boolean): this;
368
369
/** Check if function is a generator */
370
isGenerator(): boolean;
371
372
/** Set generator modifier */
373
setIsGenerator(value: boolean): this;
374
375
/** Check if function is exported */
376
isExported(): boolean;
377
378
/** Set exported */
379
setIsExported(value: boolean): this;
380
381
/** Check if function is default export */
382
isDefaultExport(): boolean;
383
384
/** Set as default export */
385
setIsDefaultExport(value: boolean): this;
386
}
387
```
388
389
### Interface Declaration
390
391
Represents an interface declaration.
392
393
```typescript { .api }
394
class InterfaceDeclaration extends Node {
395
/** Get the interface name */
396
getName(): string;
397
398
/** Set the interface name */
399
setName(name: string): this;
400
401
/** Get extends clauses */
402
getExtends(): ExpressionWithTypeArguments[];
403
404
/** Add an extends clause */
405
addExtends(text: string): ExpressionWithTypeArguments;
406
407
/** Get all properties */
408
getProperties(): PropertySignature[];
409
410
/** Add a property */
411
addProperty(structure: PropertySignatureStructure): PropertySignature;
412
413
/** Get all methods */
414
getMethods(): MethodSignature[];
415
416
/** Add a method */
417
addMethod(structure: MethodSignatureStructure): MethodSignature;
418
419
/** Get all call signatures */
420
getCallSignatures(): CallSignatureDeclaration[];
421
422
/** Add a call signature */
423
addCallSignature(structure: CallSignatureDeclarationStructure): CallSignatureDeclaration;
424
425
/** Get all construct signatures */
426
getConstructSignatures(): ConstructSignatureDeclaration[];
427
428
/** Add a construct signature */
429
addConstructSignature(structure: ConstructSignatureDeclarationStructure): ConstructSignatureDeclaration;
430
431
/** Get all index signatures */
432
getIndexSignatures(): IndexSignatureDeclaration[];
433
434
/** Add an index signature */
435
addIndexSignature(structure: IndexSignatureDeclarationStructure): IndexSignatureDeclaration;
436
}
437
```
438
439
### Variable Declaration
440
441
Represents a variable declaration.
442
443
```typescript { .api }
444
class VariableDeclaration extends Node {
445
/** Get the variable name */
446
getName(): string;
447
448
/** Set the variable name */
449
setName(name: string): this;
450
451
/** Get the type node */
452
getTypeNode(): TypeNode | undefined;
453
454
/** Set the type */
455
setType(type: string): this;
456
457
/** Get the initializer */
458
getInitializer(): Expression | undefined;
459
460
/** Set the initializer */
461
setInitializer(text: string): this;
462
463
/** Remove the initializer */
464
removeInitializer(): this;
465
}
466
467
class VariableStatement extends Node {
468
/** Get the declaration kind (const, let, var) */
469
getDeclarationKind(): VariableDeclarationKind;
470
471
/** Set the declaration kind */
472
setDeclarationKind(kind: VariableDeclarationKind): this;
473
474
/** Get all variable declarations */
475
getDeclarations(): VariableDeclaration[];
476
477
/** Add a declaration */
478
addDeclaration(structure: VariableDeclarationStructure): VariableDeclaration;
479
}
480
481
enum VariableDeclarationKind {
482
Var = "var",
483
Let = "let",
484
Const = "const",
485
}
486
```
487
488
### Import and Export Declarations
489
490
```typescript { .api }
491
class ImportDeclaration extends Node {
492
/** Get the module specifier */
493
getModuleSpecifier(): StringLiteral;
494
495
/** Set the module specifier */
496
setModuleSpecifier(text: string): this;
497
498
/** Get the import clause */
499
getImportClause(): ImportClause | undefined;
500
501
/** Get the default import */
502
getDefaultImport(): Identifier | undefined;
503
504
/** Set the default import */
505
setDefaultImport(name: string): this;
506
507
/** Get named imports */
508
getNamedImports(): ImportSpecifier[];
509
510
/** Add a named import */
511
addNamedImport(name: string): ImportSpecifier;
512
513
/** Get namespace import */
514
getNamespaceImport(): Identifier | undefined;
515
516
/** Set namespace import */
517
setNamespaceImport(name: string): this;
518
}
519
520
class ExportDeclaration extends Node {
521
/** Get the module specifier */
522
getModuleSpecifier(): StringLiteral | undefined;
523
524
/** Set the module specifier */
525
setModuleSpecifier(text: string): this;
526
527
/** Get named exports */
528
getNamedExports(): ExportSpecifier[];
529
530
/** Add a named export */
531
addNamedExport(name: string): ExportSpecifier;
532
533
/** Check if it's a namespace export */
534
isNamespaceExport(): boolean;
535
}
536
```
537
538
### Expression Nodes
539
540
Common expression node types for working with TypeScript expressions.
541
542
```typescript { .api }
543
abstract class Expression extends Node {
544
/** Get the type of this expression */
545
getType(): Type;
546
547
/** Get the symbol of this expression */
548
getSymbol(): Symbol | undefined;
549
}
550
551
class CallExpression extends Expression {
552
/** Get the expression being called */
553
getExpression(): LeftHandSideExpression;
554
555
/** Get all arguments */
556
getArguments(): Node[];
557
558
/** Add an argument */
559
addArgument(text: string): Node;
560
}
561
562
class PropertyAccessExpression extends Expression {
563
/** Get the object being accessed */
564
getExpression(): LeftHandSideExpression;
565
566
/** Get the property name */
567
getName(): Identifier;
568
}
569
570
class BinaryExpression extends Expression {
571
/** Get the left operand */
572
getLeft(): Expression;
573
574
/** Get the operator token */
575
getOperatorToken(): BinaryOperatorToken;
576
577
/** Get the right operand */
578
getRight(): Expression;
579
}
580
```
581
582
**Usage Examples:**
583
584
```typescript
585
import { Project, SyntaxKind } from "ts-morph";
586
587
const project = new Project();
588
const sourceFile = project.createSourceFile("example.ts", `
589
class MyClass {
590
private value: number = 0;
591
592
getValue(): number {
593
return this.value;
594
}
595
596
setValue(newValue: number): void {
597
this.value = newValue;
598
}
599
}
600
`);
601
602
// Get the class
603
const myClass = sourceFile.getClassOrThrow("MyClass");
604
console.log("Class name:", myClass.getName());
605
606
// Get all methods
607
const methods = myClass.getMethods();
608
console.log("Methods:", methods.map(m => m.getName()));
609
610
// Add a new method
611
myClass.addMethod({
612
name: "increment",
613
returnType: "void",
614
statements: ["this.value++;"]
615
});
616
617
// Navigate the AST
618
const valueProperty = myClass.getPropertyOrThrow("value");
619
const initializer = valueProperty.getInitializer();
620
console.log("Initial value:", initializer?.getText());
621
622
// Find nodes by syntax kind
623
const allNumbers = sourceFile.getDescendantsOfKind(SyntaxKind.NumericLiteral);
624
console.log("All numbers:", allNumbers.map(n => n.getText()));
625
```