JS Migration Guide
Assuming:
you know JavaScript.
you know patterns and build tools (e.g. webpack) used in the project.
With that assumption out of the way, in general the process consists of the following steps:
Add a
tsconfig.json
.Change your source code file extensions from
.js
to.ts
. Start suppressing errors usingany
.Write new code in TypeScript and make as little use of
any
as possible.Go back to the old code and start adding type annotations and fix identified bugs.
Use ambient definitions for third party JavaScript code.
Let us discuss a few of these points further.
Note that all JavaScript is valid TypeScript. That is to say that if you give the TypeScript compiler some JavaScript -> the JavaScript emitted by the TypeScript compiler will behave exactly the same as the original JavaScript. This means that changing the extension from .js
to .ts
will not adversely affect your codebase.
Suppressing Errors
TypeScript will immediately start TypeChecking your code and your original JavaScript code might not be as neat as you thought it was and hence you get diagnostic errors. Many of these errors you can suppress with using any
e.g.:
Even though the error is valid (and in most cases the inferred information will be better than what the original authors of different portions of the code bases imagined), your focus will probably be writing new code in TypeScript while progressively updating the old code base. Here you can suppress this error with a type assertion as shown below:
In other places you might want to annotate something as any
e.g.:
Suppressed:
Note: Suppressing errors is dangerous, but it allows you to take notice of errors in your new TypeScript code. You might want to leave
// TODO:
comments as you go along.**
Third Party JavaScript
You can change your JavaScript to TypeScript, but you can't change the whole world to use TypeScript. This is where TypeScript's ambient definition support comes in. In the beginning we recommend you create a vendor.d.ts
(the .d.ts
extension specifies the fact that this is a declaration file) and start adding dirty stuff to it. Alternatively create a file specific for the library e.g. jquery.d.ts
for jquery.
Consider the case of jquery
, you can create a trivial definition for it quite easily:
Sometimes you might want to add an explicit annotation on something (e.g. JQuery
) and you need something in type declaration space. You can do that quite easily using the type
keyword:
This provides you an easier future update path.
Third Party NPM modules
And then you can import it in your file as needed:
External non js resources
Now people can import * as foo from "./some/file.css";
Similarly if you are using html templates (e.g. angular) you can:
Last updated
Was this helpful?