MST

星途 面试题库

面试题:TypeScript中AST的基础操作

请简要描述在TypeScript编译器中,如何通过AST获取一个函数的参数列表?并给出一段简单的TypeScript代码示例,利用AST实现这一操作。
43.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
  1. 通过AST获取函数参数列表的步骤
    • 首先,使用typescript库来解析TypeScript代码生成AST(抽象语法树)。
    • 遍历AST,找到函数声明节点(ts.FunctionDeclarationts.ArrowFunction)。
    • 对于函数声明节点,访问其parameters属性,该属性包含了函数的参数列表。
  2. TypeScript代码示例
import * as ts from 'typescript';

function getFunctionParameters(sourceCode: string) {
    const sourceFile = ts.createSourceFile('example.ts', sourceCode, ts.ScriptTarget.ES5, true);
    const parameters: string[] = [];
    ts.forEachChild(sourceFile, function visitNode(node) {
        if (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node)) {
            node.parameters.forEach(param => {
                parameters.push(param.name.getText());
            });
        }
        ts.forEachChild(node, visitNode);
    });
    return parameters;
}

// 示例函数定义
const code = `function myFunction(a: number, b: string) { return a + b.length; }`;
const result = getFunctionParameters(code);
console.log(result);

在上述代码中:

  • ts.createSourceFile用于将输入的TypeScript代码解析为SourceFile对象,这是AST的根节点。
  • ts.forEachChild用于遍历AST节点,当遇到函数声明节点时,提取其参数名并存储在parameters数组中。
  • 最后,在示例代码中定义了一个函数并调用getFunctionParameters函数获取其参数列表并打印。