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

使用typescript-eslint解析无效表达式遇报错问题咨询

问题

尝试解析形如f(a; b)的无效表达式以获取对应的AST,已启用allowInvalidAST解析选项,但执行解析代码时仍抛出错误。

解析代码:

const TSParser = require('@typescript-eslint/typescript-estree');

const parse = (code) => TSParser.parse(code, {allowInvalidAST: true});

parse('f(a; b)');

抛出的错误信息:

node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js:15
        throw (0, convert_1.convertError)(parseDiagnostics[0]);
        ^

TSError: ')' expected.
    at createError (/Users/divyansh/repos/PredScript/node_modules/@typescript-eslint/typescript-estree/dist/node-utils.js:611:12)
    at convertError (/Users/divyansh/repos/PredScript/node_modules/@typescript-eslint/typescript-estree/dist/convert.js:46:41)
    at astConverter (/Users/divyansh/repos/PredScript/node_modules/@typescript-eslint/typescript-estree/dist/ast-converter.js:15:42)
    at parseWithNodeMapsInternal (/Users/divyansh/repos/PredScript/node_modules/@typescript-eslint/typescript-estree/dist/parser.js:91:66)
解决方案

allowInvalidAST选项仅能处理TypeScript已生成但存在局部错误的AST,对于f(a; b)这种存在严重语法结构错误(参数列表非法使用分号)的情况,TypeScript会直接终止解析流程,不会生成任何AST,因此该选项无法生效。

要解析这类严重无效的表达式并获取AST,需要先通过TypeScript底层API强制生成包含错误的源文件AST,再转换为ESTree格式:

const ts = require('typescript');
const TSParser = require('@typescript-eslint/typescript-estree');

const code = 'f(a; b)';
// 生成带错误的TypeScript源文件AST
const sourceFile = ts.createSourceFile(
  'test.ts',
  code,
  ts.ScriptTarget.Latest,
  true, // 启用父节点关联
  ts.ScriptKind.TS
);

// 转换为ESTree格式AST
const ast = TSParser.convert(sourceFile, {
  allowInvalidAST: true,
  errorOnUnknownASTType: false // 忽略未知AST类型的错误
});

console.log(ast);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:37:11