TypeScript is a superset of JavaScript and as such, compiles to simple JavaScript. So, why would you need to learn it? Because it adds to the language, it allows you to code JavaScript using static typing and type inference, interfaces and classes. When coding in IDEs like Visual Studio, you will be able to see errors (the famous red squiggly line) and Intellisense when typing .
Also, you don’t need to worry about the feature gap. We have all experienced this gap when watching a new release, while our company is 10 versions behind, and our browser is 5 versions behind. With TypeScript you can code once and compile to any version compliance. So you will be able to code using the latest advances of the language (based on the releases of the standard ECMAScript) without the need to worry if your final product is going to be compatible with the browser or not.
Setting Up TypeScript in Visual Studio 2015
Most likely that the version of TypeScript once you installed Visual Studio would not be the latest release. In my case, it was version 1.8.3. To check the version installed in Visual Studio you can:
- Go to Tools > Extensions and Updates.
- Find “TypeScript for Microsoft Visual Studio” and click on it.
- On the right panel, you will find the version number.
As you can read, this type of extension (TypeScript) cannot be updated automatically.
How to Update TypeScript in Visual Studio
The best way to update is to download and apply the update.
- Close all instances of Visual Studio.
- You can search for “typescript for microsoft visual studio”. Usually the first result is from Microsoft.
- The download link (at least currently) to download the latest version of TypeScript for Visual Studio 2015 is: https://www.microsoft.com/en-us/download/details.aspx?id=48593
- If you expand the “Details” tab, you can find the current version. Currently (as of October 2016) is version 2.0.3.0
- Download and install the exe.
- Open your Visual Studio.
TypeScript in Visual Studio 2015 MVC First Example
I am familar with the MVC framework so even though is not ideal as a running environment for an example or exercise, it is better to get used to it early on. There are projects (even those with just a single page) created under the MVC framework to take advantage of their features.
Let’s create a basic MVC solution in Visual Studio 2015.
- After opening Visual Studio 2015, select “New Project” to create a new project.
- Under Installed > Templates > Visual C# > Web, select “ASP.NET Web Application (.NET Framework). This is the regular ASP.NET MVC Web application, we will have fun with CORE later on.
- Write a name for your project.
- Make sure “Create a directory for solution” is checked.
- Click “OK”.
- A new pop-up window opens up “New ASP.NET Web Application”
- Choose the MVC template under ASP.NET 4.6 Templates.
- Make sure “MVC” is checked under “Add folders and core references for:”
- Add unit tests if you like.
- Click “OK” to complete the creation of your project.
Like I said before. I am used to code using the MVC templates, but you can choose any other template like “Empty” or “Single Page Application” for this exercise. It is just a matter of taste. 🙂
Creating our First TypeScript File
- To keep some order in our solution tree, I am going to create a couple of folders:
- Root\TS_Source: to keep all TypeScript (.ts) files.
- Root\Scripts\App: to keep all compiled JavaScript files for the operation of the web application.
- Right click on TS_Source folder, click on “Add”, and choose “TypeScript File”. Specify a name for Item > Let’s call this example: “example1” (no need to add the extension .ts)
- A new file “example1.ts” appears under TS_Source folder.
- Now we need to add a configuration file for TypeScript. In this file we can add all the options we need to be able to compile automatically every time we save our .ts file and choose output directories.
- Let’s select our main project (web application) to add the configuration file to our root (at the same level as Global.asax and Web.config) > Right Click > Add > “New Item”.
- Under Installed > Visual C# > Web > Choose “TypeScript JSON Configuration File”.
- Automatically the name appears as “tsconfig.json”. This default is fine.
- Basically, all the pieces are now in place. We just need one thing…. to add our code!
TypeScript Configuration File
The first thing we need to fix is our configuration file. We want Visual Studio 2015 to be able to know where the source folder is located, in what folder should put the compiled JavaScript files, and any other options required to compile TypeScript.
Here is my update tsconfig.json file:
{ "compilerOptions": { "noImplicitAny": false, "noEmitOnError": true, "removeComments": false, "sourceMap": true, "target": "es5", "outDir": "./Scripts/App" }, "files": [ "./TS_Source/example1.ts" ], "exclude": [ "node_modules", "wwwroot" ], "compileOnSave": true }
The options I updated or added from the default code present once the configuration file was created are:
- “outDir”: “./Scripts/App” – we created the App folder to hold our compiled JavaScript.
- “files”: … – This lines tells the compiler where to find the source “.ts” files.
- “compileOnSave”: – Set to “true” to compile as soon as you make changes to a .ts file and save it.
Example1.ts
So we are ready to start coding our first TypeScript file. In this example you can use some of the advanced features from TypeScript like type inference, interfaces and classes. And the great advantage.. It really looks just like JavaScript:
interface ICar { make: string; model: string; year: number; } class Car implements ICar { make: string; model: string; year: number; constructor(make: string, model: string, year: number) { this.make = make; this.model = model; this.year = year; } displayCar() { return "Car Make: " + this.make + " - Car Model: " + this.model + "- Car Year: " + this.year; } }
As soon as you save this file, it will be compile and a new file “example1.js” will appear under the APP folder. Make sure to “Show All Files” under the folder, otherwise you won’t see the file. Once you see it, you can add the file to the project.
Example1.js
As a comparison, you can see what the compiled JavaScript looks like:
var Car = (function () { function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } Car.prototype.displayCar = function () { return "Car Make: " + this.make + " - Car Model: " + this.model + "- Car Year: " + this.year; }; return Car; }()); //# sourceMappingURL=example1.js.map
What is that .map File?
Next to the “example1.js” file, you will find a “example1.js.map” file. You can also see this name in the last line of the compiled JavaScript file.
This .map file is nothing more than…. yes… a map from the javascript file to its corresponding .ts file. You can open the file and will see the following:
{"version":3,"file":"example1.js","sourceRoot":"","sources":["../../TS_Source/example1.ts"],
Using the Compiled JavaScript in our View
We are ready to use the compiled JavaScript file in our MVC View. There is no difference between the use of this compiled JavaScript file and any other not-compiled JavaScript files. Let’s take a look at our View: Index.cshtml (feel free to delete all content):
@{ ViewBag.Title = "Home Page"; } <script src="~/Scripts/App/example1.js"></script> <script> var c = new Car("Nissan", "Titan", 2010); console.debug(c.displayCar()); </script>
While coding, you will be aided by Visual Studio 2015 Intellisense, thanks in great part to TypeScript:
Now, let’s take a look at the output of Index.cshtml. If you are using IE, make sure to open Developer Tools (F12) and select the “Console” tab to be able to see the console output from our code.
That concludes our first TypeScript example. If you like this article, don’t forget to share it with your friends. Any comments or questions are always welcome.
David
Very nice example. One question, I haven’t option to choose in VS2015 “TypeScript JSON Configuration File”. Do you know the reason for this?
Thanks.
Codex Discipulus
Thanks David, my first guess will be that Typescript is not installed or did not installed correctly. Go to Tools > Extensions and Updates and check if TS is there, try uninstalling and installing back. I hope that works for you. Thanks for your question.