Type-check Your JavaScript With TypeScript
TypeScript is a superset of JavaScript with optional static typing. The DefinitelyTyped project contains type definitions for major JavaScript libraries contributed by the community. You can use these definitions and TypeScript’s compiler to check your code for errors, just by adding references.
We have a large AngularJS project. I’d like to type-check all our code and maybe find a few bugs.
Install TypeScript
Clone DefinitelyTyped to references
The DefinitelyTyped project provides type definitions for AngularJS, Jasmine and about 100 other common JavaScript libraries.
To keep it simple, I’m just going to clone the whole lot into my project, where I can reference anything I need.
Rename All .js
Files To .ts
By renaming all our files, we let tsc
and other tools know the code should be
treated as TypeScript.
Let’s give our unix skills a workout and do this with a find
one-liner:
Create References Includes For The Project
TypeScript code needs to be annotated with
You’ll need a reference for each library you’re using. To simplify things, let’s create a couple of reference files which define the shared references for our module definitions and test specs and include those in our code.
Note that test.ts
references module.ts
.
Add References To All .ts
Files
Now, let’s add the references to every TypeScript file with a couple more find
one-liners (requires GNU sed
, if you’re on OS X, install with brew install gnu-sed
--default-names
).
Phew!
The path
attribute needs to be right. Luckily, all of the code in our project
is 5 levels deep in the directory structure. If your code doesn’t have such a
regular structure, you’ll need to do something more clever.
Compile Everything With tsc
Finally, let’s run everything through the TypeScript compiler and see the issues we have to resolve:
Adding Definitions For Missing Modules
Adding type definitions for your own modules or 3rd-party modules missing from DefinitelyTyped is straightforward. A few examples: