Regrettably, as of now, TypeScript does not provide a straightforward way to access this type of information. However, TypeScript does offer a language server that can be utilized to retrieve type details. While the process is somewhat burdensome, it involves launching the server and sending specific commands to interact with projects and files before requesting information.
If you have TypeScript installed globally using npm install -g typescript
, you should be able to run the TypeScript server through the tsserver
executable. Otherwise, you can locate it within the bin
folder inside the TypeScript module.
Commands are transmitted via stdin, while responses are received on stdout in JSON format terminated by a newline character.
The initial command to send is openExternalProject
:
{"type":"request","command":"openExternalProject","arguments":{"projectFileName":"/path/to/tsconfig.json","rootFiles":[],"options":{}}}
Replace /path/to/tsconfig.json
with the actual path to your tsconfig.json
file.
The subsequent command is to open a file:
{"type":"request","command":"open","arguments":{"file":"/path/to/file.ts"}}
Lastly, utilize the quickinfo
command to retrieve type information:
{"type":"request","command":"quickinfo","arguments":{"offset":9,"line":5,"file":"/path/to/file.ts"}}
You will receive a response from the server similar to the sample below:
{"seq":0,"type":"response","command":"quickinfo","success":true,"body":{"kind":"alias","kindModifiers":"","start":{"line":5,"offset":8},"end":{"line":5,"offset":19},"displayString":"(alias) const MyComponent: new () => MyComponent\nimport MyComponent","documentation":"","tags":[]}}
For additional details on my testing request/response, refer to the provided content.
While there might be more efficient ways to communicate with the language server, this approach was devised within a limited timeframe. For further reference, explore all possible request/responses on this link.
Hopefully, this information proves helpful for your needs.