There are two popular options available for writing TypeScript code:
- Use an online playground
- Use Visual Studio 2015 and above
Online Playground
Typescriptlang.org provides a web page where we can immediately write and see JavaScript output on a web page. You can click on the Playground link.
In the left section of the page, we can write our TypeScript code, and the right section automatically converts it into JavaScript code. For example, we declare a variable num1 as a number datatype in the left section, and it is automatically updated in the right section in JavaScript code.
This page also provides examples of some features of TypeScript. Click on the drop-down above the left section and choose any example.Â
Visual Studio
Visual Studio 2015 and above already have TypeScript installed. Open a new project and choose the template “HTML Application with TypeScript,” as shown below.
In Visual Studio 2017, by default, the ‘HTML Application with TypeScript’ template is not available. You can search for online templates. Click on Online, write ‘HTML Application with TypeScript’ in the search textbox, and click on the Install button.
By default, using the above template, these 4 files are created.
- app.ts
- app.css
- index.html
- web.config
‘app.ts’ file is our typescript code file where we write our typescript code. Just build the project and then click on the ‘Show All Files’ link. Build will create two additional files:
- app.js
- app.js.map
The app.js file contains the compiled javascript code from the app.ts file, and the app.js.map file is a source map file.Â
Source Map: In production, we mainly send compressed javascript files. A source map file provides mapping code between compressed file and uncompressed file and let you see the uncompressed code during debugging.
We’ll learn more about source map files later. ‘app.js’ is already linked to the index.html file; we don’t need to do anything here.
Open the app.ts file, remove all code, and write the below code.
var var1: number = 44;
console.log('Value: ' + var1);
The above code will declare a number variable named ‘var1’ and print its value into the console window.
Build the project and run the application in Chrome. Open Developer Tools in Chrome by pressing ‘F12’ and clicking on the console tab. Result 44 is shown in the console tab, as shown below.Â
In the above section, we write some basic TypeScript code and run the application to check that our environment is setup or not.Â
In our next posts, we shall learn more about TypeScript syntax and the data types available in TypeScript.