David Dal Busco
David Dal Busco

Reputation: 8652

How to detect arrow function with the Typescript Compiler API

I try to follow TypeScript wiki example Using the Type Checker but cannot manage to identify arrow function.

e.g.:

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

Is not recognized as an arrow function type by my visitor:

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

on the contrary, standard function are identified:

e.g.

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

is recognized by the visitor with isFunctionDeclaration

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

What am I missing? How can I identify arrow function?

Upvotes: 1

Views: 556

Answers (1)

David Sherret
David Sherret

Reputation: 106660

Look at that code in ts-ast-viewer.com: https://ts-ast-viewer.com/#code/KYDwDg9gTgLgBAYwgOwM7wBbADbYnAXjgAoBKALjnSgEtkBzQgPjgHItcJWBuIA

View of AST from url above

As can be seen, there is a VariableStatement child of the SourceFile, then a VariableDeclarationList, then a VariableDeclaration and finally its initializer is an ArrowFunction.

Try going down recursively instead:

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

const arrowFunc = findDescendantArrowFunction(sourceFile);

Upvotes: 1

Related Questions