Shanon Jackson
Shanon Jackson

Reputation: 6531

Typescript - Alter AST and have it work in IDE

My knowledge of compilers, AST's and TS Language Server is limited but I'll do my best to explain.

I Want Typescript and Webstorm (My IDE) to change the type of underscore in the typescript AST to treat it as a string. This is a contrived example my real use-case is a little more complicated but I'm pretty sure if I can see how to just change it to string i can work out how to go further.

I.E

const test = _.toString()

should resolve in the IDE without issues. how can i achieve this with the typescript compiler api or any other tool?

(Note not interested in declare syntax I.E.... declare const _: string;

Iv'e had a strong search for other people doing this, and alls i can find is custom transformers but no custom AST transformations.

EDIT2: After reading Nurbols article this will not achieve what i want, it reads clearly in the first block of text that this cannot...

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

Upvotes: 0

Views: 459

Answers (1)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

You probably want Language Server Proxy/Plugin.

See this paragraph: https://github.com/Microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin#customizing-behavior

Your code should be something like (very roughly)

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;
};

I hope it is helpful, but I am not giving any guarantees that you can add completion options (in the wiki article they only remove them)

Upvotes: 1

Related Questions