【问题标题】:How to detect arrow function with the Typescript Compiler API如何使用 Typescript Compiler API 检测箭头函数
【发布时间】:2022-08-15 22:54:09
【问题描述】:

我尝试遵循 TypeScript wiki 示例 Using the Type Checker 但无法识别箭头功能。

例如。:

/**
 * Hello
 */
export const hello = (): string => \'hello\';

我的访客未将其识别为箭头函数类型:

function visit(node: ts.Node) {
   console.log(node.kind, ts.isArrowFunction(node)); // -> 236, false

相反,标准功能被识别:

例如

/**
 * Hello
 */
export function hello (): string {return \'hello\'};

被访客识别为isFunctionDeclaration

function visit(node: ts.Node) {
   console.log(node.kind, ts.isFunctionDeclaration(node)); // -> 255, true

我错过了什么?如何识别箭头功能?

  • 您可能正在检查变量声明是否是箭头函数,而不是分配给它的值?很难说,因为我们不知道您正在检查哪个节点

标签: typescript typescript-compiler-api


【解决方案1】:

查看 ts-ast-viewer.com 中的代码:https://ts-ast-viewer.com/#code/KYDwDg9gTgLgBAYwgOwM7wBbADbYnAXjgAoBKALjnSgEtkBzQgPjgHItcJWBuIA

可以看出,有一个SourceFile 的子VariableStatement,然后是VariableDeclarationList,然后是VariableDeclaration,最后它的初始化器是ArrowFunction

尝试递归下去:

function findDescendantArrowFunction(node: ts.Node) {
  if (ts.isArrowFunction(node)) {
    return node;
  } else {
    return ts.forEachChild(node, findDescendantArrowFunction);
  }
}

const arrowFunc = findDescendantArrowFunction(sourceFile);

【讨论】:

  • 太棒了,非常感谢大卫!小错字 - ts.forEachChild(node, findDescendantArrowFunction) - 但解决了我的问题?
  • 谢谢!解决它。
猜你喜欢
  • 1970-01-01
  • 2023-03-27
  • 2012-12-09
  • 2018-10-05
  • 2016-07-28
  • 1970-01-01
  • 2018-03-11
  • 2019-12-17
  • 2022-01-17
相关资源
最近更新 更多