Skip to content

基础 AST 接口

ReadonlyTextRange / TextRange

所有 AST 节点都携带源码位置信息,TextRange 是最小公共接口。

ts
interface ReadonlyTextRange {
  readonly pos: number;  // 起始偏移(含 leading trivia)
  readonly end: number;  // 结束偏移(不含)
}

interface TextRange extends ReadonlyTextRange {
  pos: number;
  end: number;
}

posend 是 UTF-16 码元偏移,与 SourceFile.text 的下标对应。


Node

Node 是整棵 AST 中每个节点的公共基类,继承 ReadonlyTextRange

ts
interface Node extends ReadonlyTextRange {
  kind: SyntaxKind;
  flags: NodeFlags;
  parent: Node;
  // ... 方法见下表
}

核心属性

成员类型说明
kindSyntaxKind节点类型枚举,唯一标识节点种类
flagsNodeFlags节点标志位(Let / Const / Ambient / Optional…)
parentNode父节点引用(Binder 阶段写入,createSourceFile 时需传 setParentNodes=true

核心方法

方法签名说明
getSourceFile(): SourceFile返回该节点所属的 SourceFile
getChildCount(sf?): number子节点数量(含 Token)
getChildAt(index, sf?): Node按索引取子节点
getChildren(sf?): Node[]全部子节点列表
getStart(sf?, includeJsDocComment?): number跳过 trivia 后的真实起始位置
getFullStart(): number含 leading trivia 的起始位置(= pos
getEnd(): number结束位置(= end
getWidth(sf?): numberend - getStart()
getFullWidth(): numberend - pos(含 trivia)
getLeadingTriviaWidth(sf?): numberleading trivia 的宽度
getFullText(sf?): string完整原始文本(含 trivia)
getText(sf?): string不含 trivia 的节点文本
forEachChild<T>(cbNode, cbNodes?): T | undefined深度优先遍历直接子节点

Declaration

Declaration 是所有声明节点的公共基接口,继承自 Node。它本身只携带一个品牌字段(用于类型系统区分),具体的名称信息由子接口 NamedDeclaration 进一步扩展。

ts
interface Declaration extends Node {
  _declarationBrand: any; // 品牌字段,仅用于类型系统区分
}

interface NamedDeclaration extends Declaration {
  readonly name?: DeclarationName; // 声明名称(可选,匿名声明时为 undefined)
}

interface DeclarationStatement extends NamedDeclaration, Statement {
  readonly name?: Identifier | StringLiteral | NumericLiteral; // 语句级声明的名称
}

继承层级

Node
└── Declaration
    └── NamedDeclaration          // 带名称的声明(绝大多数声明节点)
        └── DeclarationStatement  // 语句级声明(interface / type / enum / function 等顶层声明)

字段说明

Declaration

字段类型说明
_declarationBrandany品牌字段,仅用于 TypeScript 类型系统内部区分,不可实际访问

NamedDeclaration

字段类型说明
nameDeclarationName?声明的名称节点,匿名声明(如匿名函数、默认导出)时为 undefined

DeclarationStatement

字段类型说明
nameIdentifier | StringLiteral | NumericLiteral | undefined语句级声明的名称,范围比 NamedDeclaration.name 更窄

DeclarationName 类型

DeclarationName 是所有合法声明名称节点的联合类型:

ts
type DeclarationName =
  | PropertyName
  | JsxAttributeName
  | StringLiteralLike
  | ElementAccessExpression
  | BindingPattern
  | EntityNameExpression;

常见实现 Declaration 的节点包括:VariableDeclarationFunctionDeclarationClassDeclarationInterfaceDeclarationTypeAliasDeclarationEnumDeclarationPropertyDeclarationMethodDeclaration 等。SourceFile 也实现了 Declaration(根节点亦视为一种声明)。


SyntaxKind

SyntaxKind 是超大枚举(共约 360 个原始值),以下列出类型系统高频值

TIP

查看完整的 SyntaxKind 分类枚举,请前往 SyntaxKind 完整枚举

类型节点相关

枚举值说明
TypeParameter泛型参数 <T extends ...>
TypeReference类型引用 Array<T>Promise<T>
FunctionType函数类型 (x: T) => R
ConstructorType构造函数类型 new (...) => T
TypeQuerytypeof Expr
TypeLiteral匿名对象类型 { x: number }
ArrayType数组类型 T[]
TupleType元组类型 [A, B, C]
OptionalType可选元素 T?(元组内)
RestType剩余元素 ...T(元组内)
UnionType联合类型 A | B
IntersectionType交叉类型 A & B
ConditionalType条件类型 T extends U ? X : Y
InferTypeinfer R
ParenthesizedType括号类型 (T)
TemplateLiteralType模板字面量类型 `${T}`
NamedTupleMember具名元组成员 [name: T]
MappedType映射类型 { [K in keyof T]: ... }
LiteralType字面量类型节点
ImportTypeimport() 类型
IndexedAccessType索引访问类型 T[K]
TypePredicate类型谓词 x is T
TypeOperator类型运算符 keyof T / unique symbol / readonly

声明相关

枚举值说明
Identifier标识符(变量名、类型名等)
QualifiedNameA.B 限定名
Parameter函数参数
PropertySignature接口属性签名 { x: number }
PropertyDeclaration类属性声明
MethodSignature接口方法签名
MethodDeclaration类方法声明
IndexSignature索引签名 [key: string]: T
InterfaceDeclarationinterface 声明
TypeAliasDeclarationtype 别名声明
EnumDeclarationenum 声明

表达式中的类型相关

枚举值说明
TypeAssertionExpression<T>expr(旧式断言)
AsExpressionexpr as T
SatisfiesExpressionexpr satisfies T(TS 4.9+)
NonNullExpressionexpr!

NodeFlags

节点标志位,通过 node.flags 访问。

基础标志

标志说明
None0无标志
Let1let 声明
Const2const 声明
Using4using 声明(ES2026 Explicit Resource Management)
AwaitUsing6await using 声明
NestedNamespace8嵌套命名空间(A.B.C 形式)
Synthesized16编译器合成节点(非源码原生)
Namespace32namespace 声明
OptionalChain64可选链节点(?.
ExportContext128export 上下文
ContainsThis256包含 this 引用
HasImplicitReturn512有隐式 return
HasExplicitReturn1024有显式 return
GlobalAugmentation2048全局扩充 declare global
HasAsyncFunctions4096含异步函数
DisallowInContext8192禁止 in 运算符的上下文(如 for 初始化)
YieldContext16384yield 上下文(生成器函数体内)
DecoratorContext32768装饰器上下文
AwaitContext65536await 上下文(async 函数体内)
DisallowConditionalTypesContext131072禁止条件类型的上下文
ThisNodeHasError262144本节点存在解析错误
JavaScriptFile524288JavaScript 文件中的节点
ThisNodeOrAnySubNodesHasError1048576本节点或子节点存在错误
HasAggregatedChildData2097152子节点数据已聚合(内部缓存标志)
JSDoc16777216JSDoc 节点
JsonFile134217728JSON 文件解析模式

复合 / 合成标志

标志说明
BlockScoped7Let | Const | Using(块作用域声明)
Constant6Const | Using(不可重赋值声明)
ReachabilityCheckFlags1536HasImplicitReturn | HasExplicitReturn
ReachabilityAndEmitFlags5632ReachabilityCheckFlags | HasAsyncFunctions
ContextFlags101441536所有上下文标志的联合(DisallowInContext 等)
TypeExcludesFlags81920YieldContext | AwaitContext(类型推断时需排除的上下文)

ModifierFlags

修饰符标志位,通过 ts.getCombinedModifierFlags(node) 获取。

TIP

不要直接读 node.modifierFlagsCache,应使用 ts.getCombinedModifierFlags(node) 以确保正确合并。

标志说明
None = 0无修饰符
Exportexport
Ambientdeclare
Publicpublic
Privateprivate
Protectedprotected
Staticstatic
Readonlyreadonly
Overrideoverride(TS 4.3+)
Abstractabstract
Asyncasync
Defaultdefault
Constconst enum
Deprecated@deprecated(TS 4.0+)
Inin(映射类型修饰符,TS 4.1+)
Outout(协变标注,TS 4.7+)
Accessoraccessor(TS 4.9+)
AccessibilityModifierPublic | Private | Protected(复合)
ExportDefaultExport | Default(复合)
TypeScriptModifierTypeScript 专有修饰符集合(复合)

SourceFile

SourceFile 是解析单个 .ts / .d.ts 文件得到的根节点,也是 AST 的顶层入口。

ts
interface SourceFile extends Declaration {
  kind: SyntaxKind.SourceFile;
  statements: NodeArray<Statement>;
  endOfFileToken: Token<SyntaxKind.EndOfFileToken>;
  fileName: string;
  text: string;
  // ...
}

属性

成员类型说明
statementsNodeArray<Statement>顶层语句列表
fileNamestring文件路径(规范化)
textstring完整源码文本
isDeclarationFileboolean是否为 .d.ts 文件
hasNoDefaultLibboolean是否含 /// <reference no-default-lib>
languageVersionScriptTarget目标语言版本
languageVariantLanguageVariantStandard | JSX
scriptKindScriptKind?JS / TS / JSX / TSX / JSON
referencedFilesreadonly FileReference[]/// <reference path> 引用
typeReferenceDirectivesreadonly FileReference[]/// <reference types>
libReferenceDirectivesreadonly FileReference[]/// <reference lib>
impliedNodeFormatResolutionMode?模块模式(CJS / ESM),TS 5.x 新增

方法

方法签名说明
getLineAndCharacterOfPosition(pos): LineAndCharacter偏移 → 行列号(0-based)
getPositionOfLineAndCharacter(line, char): number行列号 → 偏移
getLineEndOfPosition(pos): number该行末尾偏移
getLineStarts(): readonly number[]各行起始偏移数组
update(newText, textChangeRange): SourceFile增量更新(Language Service 内部用)

创建方式

ts
// 仅语法解析(无类型信息,速度快)
const sf = ts.createSourceFile(
  'foo.ts',
  sourceText,
  ts.ScriptTarget.Latest,
  /*setParentNodes*/ true
);

// 含类型信息,通过 Program
const program = ts.createProgram(['foo.ts'], { strict: true });
const sf = program.getSourceFile('foo.ts')!;

NodeArray<T>

ts
interface NodeArray<T extends Node> extends ReadonlyArray<T>, ReadonlyTextRange {
  hasTrailingComma: boolean;
}

NodeArray 是带位置信息的节点数组,hasTrailingComma 表示最后一个元素后是否有逗号(对元组 / 参数列表有意义)。