Use ChatGPT to infer Typescript types from Javascript code
MIT License
Use ChatGPT to infer Typescript types from Javascript code
People converting from Javascript to Typescript end up with a lot of any
types, many of them implicit.
They don't get much value from switching to Typescript.
Even after they add annotation for primitive types like string
and number[]
, they need to create interfaces to capture their complex data.
This is a difficult step for people who have never created a type before — their knowledge of types is implicit.
Fortunately, ChatGPT is really good at working with Typescript types, and inferring them from various kinds of input.
$ export OPENAI_API_KEY=(key goes here)
$ npm ci
$ npm test
$ node dist/infer.js ~/src/example/test.js 0 100
The numeric parameters specify the start and end character locations inside the file. If they're left off the whole file is used.
This prompts ChatGPT like this:
I wrote the following Javascript code.
Can you suggest Typescript types for it? I'd like standalone interfaces if possible.
```
function parseLogsFromCsv(text) {
const lines = text.split('\n');
const logs = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const [timestamp, level, message] = line.split(',');
logs.push({ timestamp, level, message });
}
return logs;
}
```
The output is the new code should replace the old code. It contains the newly-defined interfaces as well as the existing code with type annotations added:
interface Log {
timestamp: string;
level: string;
message: string;
}
function parseLogsFromCsv(text: string): Log[] {
const lines: string[] = text.split('\n');
const logs: Log[] = [];
for (let i = 0; i < lines.length; i++) {
const line: string = lines[i];
const [timestamp, level, message]: string[] = line.split(',');
logs.push({ timestamp, level, message });
}
return logs;
}
For Hackathon:
For later: I intend to integrate the feature into VSCode's Copilot.
Convert Javascript to Typescript
Convert Javascript code to Typescript:
The prototype is simple: query ChatGPT and post-process the result slightly.