32
votes

We have an already existing JavaScript system.

What we want to do: We would like to start to integrate TypeScript into the current system; We cannot just move everything to TypeScript. We want to slowly start writing some of the new modules in TypeScript.

What we tried: We use a pattern for organizing our JS code simillar to the MODULE TypeScript construct.

We tried to rewrite a simple class/object in TypeScript and were successful but we had trouble accessing JS functions defined in our code, in other files.

Problems Encountered: We had to create dummy interfaces, and dummy functions using those interfaces etc.

So the question: can anyone comment, what would be the best approach to slowly integrate TypeScript into an existing JavaScript system.

2

2 Answers

33
votes

It sounds like you have a sensible plan. Here are my observations!

It is best to make sure you TypeScript depends on your JavaScript and not the other way around where possible. This is because it is very easy to refactor TypeScript using the Visual Studio tools, but it won't refactor JavaScript that calls your TypeScript.

You will have to write definition files for the parts of your JavaScript you need to call from TypeScript. You will need to balance the cost of writing a definition with the cost of simply converting the JavaScript to TypeScript.

If you are only calling one function, just write the definition for that one function - don't write a definition until you need it. This will keep the cost of calling your old code lower.

You could also temporarily use the any type to get away with calling anything on your JavaScript code. When you convert the file to TypeScript you will get better type checking. This is an "it depends" decision point. Rather than spending ages writing a definition, you could save the time at the cost of type checking.

For example...

declare var MyExistingClass: any;

You can now call...

var example = new MyExistingClass.Anything();
example.anythingYouLike();

You have to decide as a team whether this is acceptable or if you want to write definitions:

declare class MyExistingClass {
    anythingYouLike(): void;
}

I hope this helps.

16
votes

This is something we have recently faced moving an HTML5 game engine of about 100,000 lines of JavaScript to TypeScript. We necessarily had to do it in stages, starting by just renaming the files from .js to .ts and gradually proceeding from there. The full description is here for anyone that is interested:

http://hardcodeded.blogspot.jp/2013/02/mostly-painlessly-migrating-3d-game.html