首页 > 解决方案 > Typescript - 改变 AST 并让它在 IDE 中工作

问题描述

我对编译器、AST 和 TS 语言服务器的了解有限,但我会尽力解释。

我希望 Typescript 和 Webstorm(我的 IDE)更改 typescript AST 中的下划线类型,以将其视为字符串。这是一个人为的例子,我的真实用例稍微复杂一些,但我很确定如果我能看到如何将它更改为字符串,我可以弄清楚如何走得更远。

IE

const test = _.toString()

应该在IDE中解决没有问题。我如何使用 typescript 编译器 api 或任何其他工具来实现这一点?

(注意对声明语法不感兴趣 IE... declare const _: string;

我对其他这样做的人进行了强烈的搜索,我能找到的只是自定义转换器,但没有自定义 AST 转换。

EDIT2:阅读 Nurbols 文章后,这将无法实现我想要的,它在第一块文本中清楚地读到这不能......

Add new custom syntax to TypeScript
Change how the compiler emits JavaScript
Customize the type system to change what is or isn't an error when running tsc

标签: typescript

解决方案


您可能需要语言服务器代理/插件。

请参阅本段:https ://github.com/Microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin#customizing-behavior

您的代码应该类似于(非常粗略)

proxy.getCompletionsAtPosition = (fileName, position) => {
  const prior = info.languageService.getCompletionsAtPosition(fileName, position);
  prior.entries = prior.entries.concat(Object.keys(String.prototype));
  // of course you should research how to add subsequent
  // completion, i.e. give types to the newly added options
  return prior;
};

我希望它有帮助,但我不保证您可以添加完成选项(在 wiki 文章中他们只删除它们)


推荐阅读