A
A
Alex2021-11-12 23:15:53
typescript
Alex, 2021-11-12 23:15:53

How to programmatically get the type of a function argument?

Question from the category of code generation:
There is a pack of files. In some of them, a function is called expose(key, value). We need to analyze this batch of files and find all calls to this function. I think so here you need to twist AST. But, then you need to generate a .d.ts file with an interface in which to collect all key-value pairs.

For example:

expose('foo', 'bar')

// .d.ts
interface Window {
  foo: 'bar'
}


expose('calc', () => 1+1)

// .d.ts
interface Window {
  calc: number
}


I will figure out how to find all the necessary calls by code by analyzing ast. But I don't understand how to programmatically get the type of the second argument. After all, there may be a function, there may be a variable name or something imported ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-11-23
@Kozack

I had to file my own utility
https://github.com/cawa-93/dts-for-context-bridge

D
Dmitry Belyaev, 2021-11-13
@bingo347

You need to parse the AST and extract information from it, there are many examples here:
https://github.com/Microsoft/TypeScript/wiki/Using...
Well, here's another good article on the topic:
https://habr.com/ru/ post/457770/
Well, to study what, in general, parsers in AST issue a useful resource for different code:
https://astexplorer.net/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question