Typescript编译器API或语言服务提供了一些方法来获取函数参数的类型。以下是一种常用的方法:
ts.createSourceFile
函数创建一个TypeScript源文件对象。ts.forEachChild
函数遍历源文件中的每个节点。ts.isFunctionDeclaration
函数判断节点类型。ts.forEachChild
函数遍历函数声明节点的子节点。ts.isParameter
函数判断节点类型。ts.getTypeAtLocation
函数获取参数的类型。下面是一个示例代码,演示了如何使用TypeScript编译器API获取函数参数的类型:
import * as ts from 'typescript';
function getFunctionParameterTypes(sourceCode: string, functionName: string): ts.Type[] {
const sourceFile = ts.createSourceFile('temp.ts', sourceCode, ts.ScriptTarget.Latest);
const parameterTypes: ts.Type[] = [];
function visit(node: ts.Node) {
if (ts.isFunctionDeclaration(node) && node.name && node.name.text === functionName) {
ts.forEachChild(node, visit);
} else if (ts.isParameter(node)) {
const type = ts.getTypeAtLocation(node);
parameterTypes.push(type);
} else {
ts.forEachChild(node, visit);
}
}
visit(sourceFile);
return parameterTypes;
}
// 示例用法
const sourceCode = `
function greet(name: string, age: number) {
console.log('Hello, ' + name + '! You are ' + age + ' years old.');
}
`;
const parameterTypes = getFunctionParameterTypes(sourceCode, 'greet');
parameterTypes.forEach((type, index) => {
console.log('Parameter', index + 1, 'type:', type.getFullText());
});
在上面的示例中,getFunctionParameterTypes
函数接受两个参数:源代码和函数名。它会返回一个包含函数参数类型的数组。我们可以通过遍历数组来获取每个参数的类型信息,并打印出来。
请注意,上述示例代码仅演示了如何使用TypeScript编译器API获取函数参数的类型。在实际应用中,可能需要根据具体需求进行适当的修改和扩展。