How to convert a file in javascript format to ts format?

2

I know that the TypeScript language is used to compile files in JavaScript. But I wonder if there is any tool that makes it possible to do the reverse.

Is there any way to convert a JavaScript file to a TypeScript structure, something automatic?

For me it would be much more interesting to be able to work from the TypeScript language, to refactor a file, and to improve the logic from this, since the version we have here is very disorganized, and has a very complex and messy structure, I believe which can be merged and improved by TypeScript, since TypeScript is much more flexible in this sense.

I'm having to recreate everything manually in TypeScript, but I spend a lot of time having to check each item, and every piece of code. I would like to save effort and work from the old converted version to a strongly typed language such as TypeScript.

    
asked by anonymous 14.10.2016 / 16:05

2 answers

1

First, all JavaScript code is a valid TypeScript code, so there is no need for inverse transpilation from the compiler's point of view.

Regarding editing tools and IDEs, there is no need to rewrite the code immediately. Just change the extension from .js to .ts and you already have access to tools like static type analysis (see example below), auto-complete and refactoring.

Example 1:

// Usando TSC 2.0
if (typeof m === "number") {
    var v = m; //VS Code mostra 'm' e 'v' como do tipo number
    //...
}

Another option for not having to rewrite the whole code before using the TypeScript benefits is to create .d.ts declaration files. In these files you specify interfaces and the typing of your functions and editors can use these statements to show you the types.

Example 2:

Let's say you have a javascript code with this function:

greet({
  greeting: "hello world",
  duration: 4000
});

You can create a minhaTipagem.d.ts file with the following definition:

interface GreetingSettings {
  greeting: string;
  duration?: number;
  color?: string;
}

declare function greet(setting: GreetingSettings): void;

With this, editors will see that when you enter the greet function, it is a function that accepts a parameter of the form and type GreetingSettings .

So you can already use TypeScript typing, by writing relatively little code.

    
20.10.2016 / 01:37
1

If you have a large base of Javascript code it is recommended to use the Salsa . Basically it asks for help from the JSDoc and brings the power of the typescript to the javascript code.

[But what types?] : JSDoc to the rescue!

You can use typescript definitions from libraries, jsdoc comments, and have more or less the same power as typescript types, all without the need to change your JS code base. Of course, you can also mix js and ts files in the same project with no problem!

Here's sample nodejs project: link Notice the tsconfig.json file and optionally a ts-node to not waste time generating files.

    
04.01.2017 / 00:39