You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@typescript-eslint/parser解析TS函数:获取范围及解析报错求助

使用@typescript-eslint/parser解析TypeScript函数的问题

问题1:如何获取函数的range范围?

我正在用@typescript-eslint/parser解析TypeScript函数,想知道怎么获取该函数的range(范围)?

问题2:解析箭头函数时出现错误,如何解决?

我编写了一段读取TypeScript文件并提取函数名的脚本:

function getFunctionsFromFile(filePath) {
    const code = readFileSync(filePath, 'utf8');
    const parsed = parse(code, { loc: true }); 
    const functions = [];
    parsed.body.forEach(node => {
        if (node.type === 'FunctionDeclaration') {
            functions.push(node.id.name);
        }
    });
    return functions;
}

该脚本读取的addNumbers.ts文件内容如下:

export const addNumbers = (num1: number, num2: number) => {
  return num1 + num2
}

变量code的值为:

'export const addNumbers = (num1: number, num2: number) => {\r\n' +
    '  return num1 + num2\r\n' +
    '}\r\n'

使用parse解析时出现以下错误:

const bodyStart = this.block.body?.range[0] ?? -1;
                                                ^
TypeError: Cannot read properties of undefined (reading '0')

打印this.block.body发现它没有range属性,推测是函数解析错误。请问能否通过指定函数格式来解决这个问题?我已尝试使用TypeScript的createSourceFile,但未达预期;查阅@typescript-eslint/parser文档也未找到合适的parse参数;添加了.eslintrc.js文件也无帮助(该文件与待读取的TS项目不在同一目录)。


内容的提问来源于stack exchange,提问作者Zelda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 18:02:18