Gisway Gisway - 1 month ago 26
Javascript Question

Is there a tool to convert JavaScript files to TypeScript

Now TypeScript came out, it is an exciting news for me, but how can I convert all the existing JavaScript files to TypeScript.

lhk lhk
Answer

I fear this will be very problematic. TypeScript is a superset of JavaScript. This implies that all valid JavaScript code is also valid TypeScript code. Which is just wrong. The following code is correct in JavaScript, but creates an error in TypeScript:

var data={x:5, y:6};
data.z=5;

You can get the dynamic behaviour of JavaScript by declaring data as "ambient"

var data:any={x:5, y:6};
data.z=5;

Now this will work in TypeScript, too. Nevertheless you can change the extension of a .js file to .ts and pass this file to the TypeScript compiler. This really confused me and I asked the question in the TypeScript IRC channel on freenode. It turned out that the Typescript compiler checks its input for valid JavaScript and just doesn't do anything in case it finds something. Intuitively this sounds good. You should be able to "convert" all your JavaScript to Typescript by merely updating the file extensions and be good to go. Unfortunately this doesn't work as expected. Let's assume you've got this code:

var func=function(n){alert(n)};

var data={x:5};
data.z=6;

Edit: I've just tried to compile this and it doesn't work. I'm sorry, I seem to have been mistaken: The TypeScript compiler doesn't even accept pure JavaScript. I'll try to find out what went wrong.

You've changed the file extension to .ts and use the function func in your other code. At first everything seems fine but then an ugly bug turns up. You decide that some static type checking would probably help you and you change the code to:

var func=function(n:string){alert(n)};

var data={x:5};
data.z=6;

But now this is no longer valid JavaScript code and will cause the compiler to generate lots of error messages. After all data has no member "z". ... This behaviour could be avoided if the default type would always "any" but then type inference would be utterly useless.

So how do you solve this problem ? The answer is: declaration files. You can use your JavaScript code "as is" in the project and still get static type checking with the help of a few .d.ts files. They inform the compiler what variables, methods and "classes" are declared in a JavaScript file, including their types. Therefore they allow for compile-time type checking and fantastic intellisense. A .d.ts file for my example would be

declare var data:any;
declare function func(n:string);

Save this as "myjsfile.d.ts" and import it to typescript with

///<reference path="myjsfile.d.ts"/>

be sure to include the JavaScript script in your html file above the compiled typescript. Here's an interesting link. You might be interested in the section "Turning JavaScript into TypeScript".

Comments