TLDR: Use typings install –ambient <name of framework> to install type definitions
I’m still pretty new to TypeScript and trying to get the hang of things. One thing I’ve had a difficult time with is getting type definitions. Most of the blog posts I could find point me towards DefinitelyTyped, a repository for TypeScript definitions. Unfortunately, this is out of date, and NPM notifies you of this when you try to install it with the command npm install -g tsd .
Instead, you’re encouraged to use Typings.
I then used the following command to install Typings:
# Install Typings CLI utility. npm install typings --global
Afterwards, you’ll be greeted with this message, notifying you that it’s installing:
Typings or DefinitelyTyped?
Now here’s where things get confusing. I can find any package I need from Definitely Typed. I can just enter TSD install jquery and it will locate, download, and install that type definition at typings/jquery/jquery.d.ts.
Works well! So why does DefinitelyTyped say to use Typings? Even more bizarre, if you try to search for which type definitions are available to typings, it only lists these:
typings install npm jquery
Yeah, it’s not there.
But wait…. what is this noise about using “–ambient”? I don’t even know what that is.
typings install --ambient jquery
So it got the jQuery type definition from the remote DefinitelyTyped repository, and installed it in my local project.
Probably not the command I would have used to install it, but it is what it is.
Referencing the type definition from within your TypeScript file
One last step! You need to make your TypeScript file aware of the definitions. In my case, I’m creating a file called map.ts, and I need to add the reference to jQUery within it. Without this reference, TypeScript will throw a warning, stating that it doesn’t know what the $ means.
Now, I add the reference at the top of my map.ts file, and that red squiggly goes away!
/// <reference path="../../typings/main/ambient/jquery/jquery.d.ts" />
Note that the ../../ are escape sequences, so that I can navigate to the correct directory. It is basically saying “Right now I am located two folders deep in this project. I need to back out two folders, which brings me into the root directory. From there I can go to typings/main/ambient/jquery/jquery.d.ts“.
This is because my map.ts file is located inside of public/js folder, so I need to escape those and get back to the root directory.
I wrote this because the instructions were not clear at all, on either the Typings site or DefinitelyTyped. If you could this to be helpful, please let me know. I’ll continue to blog about my trials and tribulations into the world of TypeScript from here! The code for this project can be found in this repository.