Monday, 27 February 2017

Getting started with TypeScript

What is TypeScript?

TypeScript is a typed superset of Javascript that compiles to plain JavaScript. It adds static typing, using type Annotation, which enables type checking at the compile-time and also adds class-based OOPS concepts to JavaScript. As we know, TypeScript is a superset of JavaScript, which makes any JavaScript program a valid TypeScript program. It is free, open source and a cross-platform programming language developed and maintained by Microsoft. Even AngularJS 2.0 is written in TypeScript.


In this article, we will use Visual Studio code editor to create a Hello world Application in TypeScript.

Let’s begin
Go to https://nodejs.org/en/ and Download Node.js (which is a JavaScript runtime built on Chrome’s V8 runtime engine).
Once the download is complete, install Node.js.

Now, open CMD prompt in order to install TypeScript. We will use NPM (Node Package Manager) to install TypeScript. (In image 1 given below, the command is used to install the latest stable TypeScript version and 2 is editors used for TypeScript).
Type NPM install -g TypeScript command.
Type tsc -version in order to check the installed version of TypeScript.
There are several code editors available like Visual Studio code, Sublime, WebStorm, Eclipse, Vim, etc. In this series, we will use Visual Studio code as a code editor. Visit https://code.visualstudio.com/ and click Download.
Install Visual Studio code editor.
After installing, click Explorer icon and then click Open Folder. I have created a folder named as HelloWorldinTS. Click Select Folder.
Click Add New File and name it as app.ts (You can name it, as you want).
Add the code given below in app.ts.

class MyFirstApp {
    _Name: string;
    constructor(public Name: string) {
        this._Name = Name;
    }
    ShowHelloMessage() {
        console.log("Hello " + this._Name)
    }
}
let objMyFirstApp = new MyFirstApp("Anoop");
objMyFirstApp.ShowHelloMessage(); 
Here, I have created a class with a constructor which takes name parameter of type string and a method, which prints Hello [Name] as an output on the console. Subsequently, I created objMyFirstApp object of that class and invoked ShowHelloMessage (We will learn in depth about each thing in my upcoming article on TypeScript).

Now, press Crtl+Shift+P to open the command palette, type Tasks and select Run Build Task (We can compile it, using tsc in the command prompt but, in this article, I will show you how to compile or build it using Visual Studio code). Select Run Build Task (or Press Crtl+Shift+B).
After clicking, you will see an alert, i.e. no task runner is configured. Click Configure Task Runner.
Now, select TypeScript to create tasks.json file in your Workspace .vscode folder.
/div>
Whenever we build our code, it will use tsc command (The command tsc assumes that tsc has been installed, using npm install -g TypeScript) with several arguments like target ES5, outDir as js (I want to store compiled *.js code in js folder), watch will detect the changes and compile the code on saving. I want app.ts file to be compiled.

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558 
    // for the documentation about the tasks.json format 
    "version": "0.1.0",
        "command": "tsc",
            "isShellCommand": true,
                "args": ["--target", "ES5",
                    "--outDir", "js",
                    "--sourceMap",
                    "--watch",
                    "app.ts"],
                    "showOutput": "silent",
                        "isWatching": true,
                            "problemMatcher": "$tsc-watch"
Now, press Crtl+Shift+B in order to run build task. You will see JS directory is created in your Workspace folder with app.js file. As we set tsc in watch mode, whenever we change and save our TypeScript Code, it will be compiled immediately.

Integrating Debugger in Visual Studio code 
Now, I want to debug my code or want to see the output in Visual Studio code’s console. Click Debug icon on the left side of Visual Studio code and Click the little gear icon (i.e. Open launch.json file). Visual Studio code automatically detects your development environment. 
Visual Studio code supports debugging a program in launch or attaching it to the already running program. Here, I mentioned the program files and outFiles location in launch.json file.

{
    // Use IntelliSense to learn about possible Node.js debug attributes. 
    // Hover to view descriptions of existing attributes. 
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 
    "version": "0.2.0",
        "configurations": [
            {
                "type": "node",
                "request": "launch",
                "name": "Launch Program",
                "program": "${workspaceRoot}/app.ts",
                "cwd": "${workspaceRoot}",
                "outFiles": ["${workspaceRoot}/js/*.js"]
            },
            {
                "type": "node",
                "request": "attach",
                "name": "Attach to Process",
                "port": 5858,
                "outFiles": []
            }
        ]
}  
Now, hit F5. You will see the output on Debug console of VS code.

We can also set the breakpoints in order to debug the code at a particular step and use step in/out, step over and other things for debugging purposes.
Hope you like it. Thanks
[Download Source Code via Google Drive]

0 comments:

Post a Comment

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+