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?
Look at that code in ts-ast-viewer.com: https://ts-ast-viewer.com/#code/KYDwDg9gTgLgBAYwgOwM7wBbADbYnAXjgAoBKALjnSgEtkBzQgPjgHItcJWBuIA
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);