HTML5 Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 151 posts at DZone. You can read more from them at their website. View Full User Profile

Quick Tip – TypeScript Declare Keyword

07.23.2013
| 1704 views |
  • submit to reddit

 Last week, Yaniv Rodenski and I delivered a TypeScript session in WDC.IL user group. One of the things we showed during the session was the declare keyword. In this short quick tip, I’ll describe what is this keyword and where to use it.

If It Doesn’t Exists, Declare It

Not all JavaScript libraries/frameworks have TypeScript declaration files. On the other hand, we might want to use libraries/frameworks in our TypeScript files without getting compilation errors. What can we do?
One solution is to use the declare keyword. The declare keyword is used for ambient declarations where you want to define a variable that may not have originated from a TypeScript file.

For example, lets imagine that we have a library called myLibrary that doesn’t have a TypeScript declaration file and have a namespace called myLibrary in the global namespace. If you want to use that library in your TypeScript code, you can use the following code:

declare var myLibrary;

The type that the TypeScript runtime will give to myLibrary variable is the any type. The problem here is that you won’t have Intellisense for that variable in design time but you will be able to use the library in your code. Another option to have the same behavior without using the declare keyword is just using a variable with the any type:

var myLibrary: any;

Both of the code examples will result in the same JavaScript output but the declare example is more readable and expresses an ambient declaration.

Summary

The TypeScript declare keyword is used to declare variables that may not have originated from a TypeScript file.

Published at DZone with permission of Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)