util.d.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. import * as ts from 'typescript';
  2. import { NodeWrap } from './convert-ast';
  3. export declare function getChildOfKind<T extends ts.SyntaxKind>(node: ts.Node, kind: T, sourceFile?: ts.SourceFile): ts.Token<T> | undefined;
  4. export declare function isTokenKind(kind: ts.SyntaxKind): boolean;
  5. export declare function isNodeKind(kind: ts.SyntaxKind): boolean;
  6. export declare function isAssignmentKind(kind: ts.SyntaxKind): boolean;
  7. export declare function isTypeNodeKind(kind: ts.SyntaxKind): boolean;
  8. export declare function isJsDocKind(kind: ts.SyntaxKind): boolean;
  9. export declare function isKeywordKind(kind: ts.SyntaxKind): boolean;
  10. export declare function isThisParameter(parameter: ts.ParameterDeclaration): boolean;
  11. export declare function getModifier(node: ts.Node, kind: ts.Modifier['kind']): ts.Modifier | undefined;
  12. export declare function hasModifier(modifiers: ts.ModifiersArray | undefined, ...kinds: Array<ts.Modifier['kind']>): boolean;
  13. export declare function isParameterProperty(node: ts.ParameterDeclaration): boolean;
  14. export declare function hasAccessModifier(node: ts.ClassElement | ts.ParameterDeclaration): boolean;
  15. export declare const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean;
  16. export declare const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean;
  17. export declare const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean;
  18. export declare function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags): boolean;
  19. export declare function isModifierFlagSet(node: ts.Node, flag: ts.ModifierFlags): boolean;
  20. export declare function getPreviousStatement(statement: ts.Statement): ts.Statement | undefined;
  21. export declare function getNextStatement(statement: ts.Statement): ts.Statement | undefined;
  22. /** Returns the token before the start of `node` or `undefined` if there is none. */
  23. export declare function getPreviousToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
  24. /** Returns the next token that begins after the end of `node`. Returns `undefined` for SourceFile and EndOfFileToken */
  25. export declare function getNextToken(node: ts.Node, sourceFile?: ts.SourceFile): ts.Node | undefined;
  26. /** Returns the token at or following the specified position or undefined if none is found inside `parent`. */
  27. export declare function getTokenAtPosition(parent: ts.Node, pos: number, sourceFile?: ts.SourceFile, allowJsDoc?: boolean): ts.Node | undefined;
  28. /**
  29. * Return the comment at the specified position.
  30. * You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
  31. * If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
  32. */
  33. export declare function getCommentAtPosition(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): ts.CommentRange | undefined;
  34. /**
  35. * Returns whether the specified position is inside a comment.
  36. * You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
  37. * If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
  38. */
  39. export declare function isPositionInComment(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): boolean;
  40. export declare function commentText(sourceText: string, comment: ts.CommentRange): string;
  41. /** Returns the deepest AST Node at `pos`. Returns undefined if `pos` is outside of the range of `node` */
  42. export declare function getAstNodeAtPosition(node: ts.Node, pos: number): ts.Node | undefined;
  43. /**
  44. * Returns the NodeWrap of deepest AST node that contains `pos` between its `pos` and `end`.
  45. * Only returns undefined if pos is outside of `wrap`
  46. */
  47. export declare function getWrappedNodeAtPosition(wrap: NodeWrap, pos: number): NodeWrap | undefined;
  48. export declare function getPropertyName(propertyName: ts.PropertyName): string | undefined;
  49. export declare function forEachDestructuringIdentifier<T>(pattern: ts.BindingPattern, fn: (element: ts.BindingElement & {
  50. name: ts.Identifier;
  51. }) => T): T | undefined;
  52. export declare function forEachDeclaredVariable<T>(declarationList: ts.VariableDeclarationList, cb: (element: (ts.VariableDeclaration | ts.BindingElement) & {
  53. name: ts.Identifier;
  54. }) => T): T | undefined;
  55. export declare enum VariableDeclarationKind {
  56. Var = 0,
  57. Let = 1,
  58. Const = 2
  59. }
  60. export declare function getVariableDeclarationKind(declarationList: ts.VariableDeclarationList): VariableDeclarationKind;
  61. export declare function isBlockScopedVariableDeclarationList(declarationList: ts.VariableDeclarationList): boolean;
  62. export declare function isBlockScopedVariableDeclaration(declaration: ts.VariableDeclaration): boolean;
  63. export declare function isBlockScopedDeclarationStatement(statement: ts.Statement): statement is ts.DeclarationStatement;
  64. export declare function isInSingleStatementContext(statement: ts.Statement): boolean;
  65. export declare enum ScopeBoundary {
  66. None = 0,
  67. Function = 1,
  68. Block = 2,
  69. Type = 4,
  70. ConditionalType = 8
  71. }
  72. export declare enum ScopeBoundarySelector {
  73. Function = 1,
  74. Block = 3,
  75. Type = 7,
  76. InferType = 8
  77. }
  78. export declare function isScopeBoundary(node: ts.Node): ScopeBoundary;
  79. export declare function isTypeScopeBoundary(node: ts.Node): ScopeBoundary;
  80. export declare function isFunctionScopeBoundary(node: ts.Node): ScopeBoundary;
  81. export declare function isBlockScopeBoundary(node: ts.Node): ScopeBoundary;
  82. /** Returns true for scope boundaries that have their own `this` reference instead of inheriting it from the containing scope */
  83. export declare function hasOwnThisReference(node: ts.Node): boolean;
  84. export declare function isFunctionWithBody(node: ts.Node): node is ts.FunctionLikeDeclaration & {
  85. body: {};
  86. };
  87. /**
  88. * Iterate over all tokens of `node`
  89. *
  90. * @param node The node whose tokens should be visited
  91. * @param cb Is called for every token contained in `node`
  92. */
  93. export declare function forEachToken(node: ts.Node, cb: (node: ts.Node) => void, sourceFile?: ts.SourceFile): void;
  94. export declare type ForEachTokenCallback = (fullText: string, kind: ts.SyntaxKind, range: ts.TextRange, parent: ts.Node) => void;
  95. /**
  96. * Iterate over all tokens and trivia of `node`
  97. *
  98. * @description JsDoc comments are treated like regular comments
  99. *
  100. * @param node The node whose tokens should be visited
  101. * @param cb Is called for every token contained in `node` and trivia before the token
  102. */
  103. export declare function forEachTokenWithTrivia(node: ts.Node, cb: ForEachTokenCallback, sourceFile?: ts.SourceFile): void;
  104. export declare type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void;
  105. /** Iterate over all comments owned by `node` or its children */
  106. export declare function forEachComment(node: ts.Node, cb: ForEachCommentCallback, sourceFile?: ts.SourceFile): void;
  107. export interface LineRange extends ts.TextRange {
  108. contentLength: number;
  109. }
  110. export declare function getLineRanges(sourceFile: ts.SourceFile): LineRange[];
  111. /** Get the line break style used in sourceFile. This function only looks at the first line break. If there is none, \n is assumed. */
  112. export declare function getLineBreakStyle(sourceFile: ts.SourceFile): "\n" | "\r\n";
  113. /**
  114. * Determines whether the given text parses as a standalone identifier.
  115. * This is not a guarantee that it works in every context. The property name in PropertyAccessExpressions for example allows reserved words.
  116. * Depending on the context it could be parsed as contextual keyword or TypeScript keyword.
  117. */
  118. export declare function isValidIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
  119. /**
  120. * Determines whether the given text can be used to access a property with a PropertyAccessExpression while preserving the property's name.
  121. */
  122. export declare function isValidPropertyAccess(text: string, languageVersion?: ts.ScriptTarget): boolean;
  123. /**
  124. * Determines whether the given text can be used as unquoted name of a property declaration while preserving the property's name.
  125. */
  126. export declare function isValidPropertyName(text: string, languageVersion?: ts.ScriptTarget): boolean;
  127. /**
  128. * Determines whether the given text can be parsed as a numeric literal.
  129. */
  130. export declare function isValidNumericLiteral(text: string, languageVersion?: ts.ScriptTarget): boolean;
  131. /**
  132. * Determines whether the given text can be used as JSX tag or attribute name while preserving the exact name.
  133. */
  134. export declare function isValidJsxIdentifier(text: string, languageVersion?: ts.ScriptTarget): boolean;
  135. export declare function isNumericPropertyName(name: string | ts.__String): boolean;
  136. export declare function isSameLine(sourceFile: ts.SourceFile, pos1: number, pos2: number): boolean;
  137. export declare enum SideEffectOptions {
  138. None = 0,
  139. TaggedTemplate = 1,
  140. Constructor = 2,
  141. JsxElement = 4
  142. }
  143. export declare function hasSideEffects(node: ts.Expression, options?: SideEffectOptions): boolean;
  144. /** Returns the VariableDeclaration or ParameterDeclaration that contains the BindingElement */
  145. export declare function getDeclarationOfBindingElement(node: ts.BindingElement): ts.VariableDeclaration | ts.ParameterDeclaration;
  146. export declare function isExpressionValueUsed(node: ts.Expression): boolean;
  147. export declare enum AccessKind {
  148. None = 0,
  149. Read = 1,
  150. Write = 2,
  151. Delete = 4,
  152. ReadWrite = 3,
  153. Modification = 6
  154. }
  155. export declare function getAccessKind(node: ts.Node): AccessKind;
  156. export declare function isReassignmentTarget(node: ts.Expression): boolean;
  157. export declare function canHaveJsDoc(node: ts.Node): node is ts.HasJSDoc;
  158. /** Gets the JSDoc of a node. For performance reasons this function should only be called when `canHaveJsDoc` returns true. */
  159. export declare function getJsDoc(node: ts.Node, sourceFile?: ts.SourceFile): ts.JSDoc[];
  160. /**
  161. * Parses the JsDoc of any node. This function is made for nodes that don't get their JsDoc parsed by the TypeScript parser.
  162. *
  163. * @param considerTrailingComments When set to `true` this function uses the trailing comments if the node starts on the same line
  164. * as the previous node ends.
  165. */
  166. export declare function parseJsDocOfNode(node: ts.Node, considerTrailingComments?: boolean, sourceFile?: ts.SourceFile): ts.JSDoc[];
  167. export declare enum ImportKind {
  168. ImportDeclaration = 1,
  169. ImportEquals = 2,
  170. ExportFrom = 4,
  171. DynamicImport = 8,
  172. Require = 16,
  173. ImportType = 32,
  174. All = 63,
  175. AllImports = 59,
  176. AllStaticImports = 3,
  177. AllImportExpressions = 24,
  178. AllRequireLike = 18
  179. }
  180. export declare function findImports(sourceFile: ts.SourceFile, kinds: ImportKind, ignoreFileName?: boolean): (ts.StringLiteral | ts.NoSubstitutionTemplateLiteral)[];
  181. export declare type ImportLike = ts.ImportDeclaration | ts.ImportEqualsDeclaration & {
  182. moduleReference: ts.ExternalModuleReference;
  183. } | ts.ExportDeclaration & {
  184. moduleSpecifier: {};
  185. } | ts.CallExpression & {
  186. expression: ts.Token<ts.SyntaxKind.ImportKeyword> | ts.Identifier & {
  187. text: 'require';
  188. };
  189. arguments: [ts.Expression, ...ts.Expression[]];
  190. } | ts.ImportTypeNode;
  191. export declare function findImportLikeNodes(sourceFile: ts.SourceFile, kinds: ImportKind, ignoreFileName?: boolean): ImportLike[];
  192. /**
  193. * Ambient context means the statement itself has the `declare` keyword
  194. * or is inside a `declare namespace`, `delcare module` or `declare global`.
  195. */
  196. export declare function isStatementInAmbientContext(node: ts.Statement): boolean;
  197. /** Includes `declare namespace`, `declare module` and `declare global` and namespace nested in one of the aforementioned. */
  198. export declare function isAmbientModuleBlock(node: ts.Node): node is ts.ModuleBlock;
  199. export declare function getIIFE(func: ts.FunctionExpression | ts.ArrowFunction): ts.CallExpression | undefined;
  200. export declare type StrictCompilerOption = 'noImplicitAny' | 'noImplicitThis' | 'strictNullChecks' | 'strictFunctionTypes' | 'strictPropertyInitialization' | 'alwaysStrict' | 'strictBindCallApply';
  201. export declare function isStrictCompilerOptionEnabled(options: ts.CompilerOptions, option: StrictCompilerOption): boolean;
  202. export declare type BooleanCompilerOptions = {
  203. [K in keyof ts.CompilerOptions]: NonNullable<ts.CompilerOptions[K]> extends boolean ? K : never;
  204. } extends {
  205. [_ in keyof ts.CompilerOptions]: infer U;
  206. } ? U : never;
  207. /**
  208. * Checks if a given compiler option is enabled.
  209. * It handles dependencies of options, e.g. `declaration` is implicitly enabled by `composite` or `strictNullChecks` is enabled by `strict`.
  210. * However, it does not check dependencies that are already checked and reported as errors, e.g. `checkJs` without `allowJs`.
  211. * This function only handles boolean flags.
  212. */
  213. export declare function isCompilerOptionEnabled(options: ts.CompilerOptions, option: BooleanCompilerOptions | 'stripInternal'): boolean;
  214. /**
  215. * Has nothing to do with `isAmbientModuleBlock`.
  216. *
  217. * @returns `true` if it's a global augmentation or has a string name.
  218. */
  219. export declare function isAmbientModule(node: ts.ModuleDeclaration): boolean;
  220. /**
  221. * @deprecated use `getTsCheckDirective` instead since `// @ts-nocheck` is no longer restricted to JS files.
  222. * @returns the last `// @ts-check` or `// @ts-nocheck` directive in the given file.
  223. */
  224. export declare function getCheckJsDirective(source: string): ts.CheckJsDirective | undefined;
  225. /** @returns the last `// @ts-check` or `// @ts-nocheck` directive in the given file. */
  226. export declare function getTsCheckDirective(source: string): ts.CheckJsDirective | undefined;
  227. export declare function isConstAssertion(node: ts.AssertionExpression): boolean;
  228. /** Detects whether an expression is affected by an enclosing 'as const' assertion and therefore treated literally. */
  229. export declare function isInConstContext(node: ts.Expression): boolean;
  230. /** Returns true for `Object.defineProperty(o, 'prop', {value, writable: false})` and `Object.defineProperty(o, 'prop', {get: () => 1})`*/
  231. export declare function isReadonlyAssignmentDeclaration(node: ts.CallExpression, checker: ts.TypeChecker): boolean;
  232. /** Determines whether a call to `Object.defineProperty` is statically analyzable. */
  233. export declare function isBindableObjectDefinePropertyCall(node: ts.CallExpression): boolean;
  234. export interface WellKnownSymbolLiteral extends ts.PropertyAccessExpression {
  235. expression: ts.Identifier & {
  236. text: 'Symbol';
  237. escapedText: 'symbol';
  238. };
  239. }
  240. export declare function isWellKnownSymbolLiterally(node: ts.Expression): node is WellKnownSymbolLiteral;
  241. export interface PropertyName {
  242. displayName: string;
  243. symbolName: ts.__String;
  244. }
  245. /** @deprecated typescript 4.3 removed the concept of literal well known symbols. Use `getPropertyNameFromType` instead. */
  246. export declare function getPropertyNameOfWellKnownSymbol(node: WellKnownSymbolLiteral): PropertyName;
  247. export interface LateBoundPropertyNames {
  248. /** Whether all constituents are literal names. */
  249. known: boolean;
  250. names: PropertyName[];
  251. }
  252. export declare function getLateBoundPropertyNames(node: ts.Expression, checker: ts.TypeChecker): LateBoundPropertyNames;
  253. export declare function getLateBoundPropertyNamesOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): LateBoundPropertyNames;
  254. /** Most declarations demand there to be only one statically known name, e.g. class members with computed name. */
  255. export declare function getSingleLateBoundPropertyNameOfPropertyName(node: ts.PropertyName, checker: ts.TypeChecker): PropertyName | undefined;
  256. export declare function unwrapParentheses(node: ts.Expression): ts.Expression;
  257. export declare function formatPseudoBigInt(v: ts.PseudoBigInt): `${string}n` | `-${string}n`;
  258. /**
  259. * Determines whether the given `SwitchStatement`'s `case` clauses cover every possible value of the switched expression.
  260. * The logic is the same as TypeScript's control flow analysis.
  261. * This does **not** check whether all `case` clauses do a certain action like assign a variable or return a value.
  262. * This function ignores the `default` clause if present.
  263. */
  264. export declare function hasExhaustiveCaseClauses(node: ts.SwitchStatement, checker: ts.TypeChecker): boolean;
  265. export declare function getBaseOfClassLikeExpression(node: ts.ClassLikeDeclaration): ts.ExpressionWithTypeArguments | undefined;