面试题答案
一键面试- 通过AST获取函数参数列表的步骤:
- 首先,使用
typescript
库来解析TypeScript代码生成AST(抽象语法树)。 - 遍历AST,找到函数声明节点(
ts.FunctionDeclaration
或ts.ArrowFunction
)。 - 对于函数声明节点,访问其
parameters
属性,该属性包含了函数的参数列表。
- 首先,使用
- 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
函数获取其参数列表并打印。