Introduction to typescript and Angular2


typescript-logo-585x200

What is Typescript?
Typescript is a free and open source programming language developed and maintained by Microsoft,Typescript is a superset of JavaScript
download
Typescript files are compiled to readable JavaScript and there is a source map associated with each each JavaScript file, what are these files it is described later for now lets discussed the benefits of using Typescript
1.Big advantage of Typescript is we identify Type related issues early before going to production:unit test will fail before going to production as it is statically typed
2.You can even set the js versionn that you want the resulting js file into be
3.we can use all object oriented features such as interface,class and abstraction
images
Typescript Javascript
Typescript is statically typed Javascript is dynamically typed
Typescript has function overloading it does not support function overloading
Typescript is optionally typed JavaScript has no datatype declaration
Typescript is fully object oriented JavaScript is not fully object oriented
For a large JavaScript project, adopting Typescript might result in more robust software, while still being deployable where a regular JavaScript application would run. become difficult to understand in case of a large project
new(1)
Typescript Coffiescript
  • Built-in type annotations let you document interfaces and enforce their correctness at compile time, cutting down on logical errors
Coffiescript is Dynamically Typed Language
Typescript is object oriented Minimalistic syntax with lots of syntax sugar

Typescript vs Scalajs

Defining classes in Typescript
class Employee{
constructor(public name:String,public lastName:Sring){}
fullName(){
return '${this.name}${this.fullName}';
}}
Defining classes in Scala.js

class Employee(public firstName:String,public lastName:Sring){
def fullName():String={
return s"${firstName}${lastName}";
}}
Fat arrow functions in Typescript
const names = employee.map{k =>k.firstName}
Fat arrow functions in Scala.js
const names = employee.map{_.name}

 

Usage of Collections in Typescript
const employeeMap = new Map<number,Employee>
([101,new Employee("anubhav" ,"tarar")],[102,new Employee("aj","styles")])
const names = new Array<String>
for(const[key,person] of employeeMap)
{
if(key>100)
{
names.push ('${key}= ${person.firstName}');
}
Usage of Collections in Scalajs

val employeeMap = Map(101->new Employee(“anubhav”,”tarar”), ,102->new Employee(“aj”,”styles”) ) val names – for( (key,emp) <- employeeMap if(key>100)}yield s”$key = ${emp.firstName}”

typescript-vs-coffeescript-vs-es6-1-638

ES6 is the next iteration of JavaScript, but it does not run in today’s browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still an dynamic (read: untyped) language.

Typescript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, Typescript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today’s browsers.

Features Of Typescript
Type Annotation:
using type annotation we can assigned a particular type to a variable
var id:number =123;

 

Dynamic Type:
Typescript is optionally statically typed programming language. The types are checked in order to prevent assignment of invalid values in term of their types.
We can optionally change the variable into a dynamic one.
var demo:any =5;
demo =”john”;
demo = new Object();
Automatic Type Inferring:
When assigning a variable, that was just created, with a value, the TypeScript execution environment automatically identifies the type and from that moment on the type of that variable is unchanged.
var demo = 1;
demo =’abc’ // result in compilation error

 

Type Eraser:
When compiling the Typescript code into JavaScript all of the type annotations are removed.

 

App.ts
var a: number = 3;
var b: string = ‘abc’;
App.js after Compilation
var a = 3;
var b = ‘abc’;

 

Constructor
When we define a new class it automatically has a constructor. The default one. We can define a new constructor. When doing so, the default one will be
deleted.When we define a new constructor we can specify each one of its parameters with an access modifier and by doing so indirectly define those parameters as instance variables
class Person {
constructor(public name:String){
this.name = name;}
greet():String={
return “my name is”+this.name);
}
}
var person = new Person(“john);
Console.log(person.greet);

 

Interface:
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: “Size 10 Object”};
printLabel(myObj);
The interface LabelledValue is a name we can now use to describe the requirement in the previous example.
It still represents having a single property called label that is of type string.
Notice: we didn’t have to explicitly say that the object we pass to printLabel implements this interface like we might have to in other languages. Here, it’s only the shape that matters. If the object we pass to the function meets the requirements listed, then it’s allowed.
Function overloading(ts file)
you have to first write a method declaration for each of the overloads and then one method implementation that checks its arguments to decide which overload was called. The signature of the implementation has to be compatible with all of the overloads.
class Customer {
name: string;
Id: number;
add(Id: number);
add(name:string);
add(value: any) {
if (value && typeof value == “number”) {
//Do something
}
if (value && ttypeof value == “string”) {
//Do Something
}
}
}

 

Function overloading(js file)
var Customer = (function () {
function Customer() {
}
Customer.prototype.add = function (value) {
if (value && typeof value == “number”) {
}
if (value && typeof value == “string”) {
}
};
return Customer;
}());

 

Typescript Support Optional Properties
In JavaScript, every parameter is considered optional. If no value is supplied, then it is treated as undefined. So while writing in Typescript, we can make a parameter optional using the “?” after the parameter name.
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: “white”, area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: “black”});

 

How to Install typeScript:
1.install git
2.install nodejs
3.install typescript by command
npm install -g typescript
4.install typescript defination manager
npm install -g typescript tsd
5.install typescript compiler
npm install typescript-compiler
QUESTION ARISES WHAT IS TSD?
Typescript Definition Manager (TSD) is a package manager to search and install Typescript definition files directly from the community driven DefinitelyTyped repository. Let’s see with an example.
Suppose, you want to use some jQuery code in your .ts file.
$(document).ready (function() { //Your jQuery code });
and now when you try to compile it using tsc, you will get compile time error Cannot find name “$”. That’s because Typescript can’t understand what does “$” means. So somehow we need to inform Typescript compiler that it belongs to jQuery. That’s where TSD comes into play. You can download jQuery Type Definition file and include it in your .ts file.
How Do You Compile Typescript Files?
The extension for any Typescript file is “.ts”. And any JavaScript file is TypeScript file as it is a superset of JavaScript. So change extension of “.js” to “.ts” file and your TypeScript file is ready. To compile any .ts file into .js, use the following command.
tsc <Typescript File Name>
For example, to compile “Helloworld.ts”:
tsc helloworld.ts
And the result would be helloworld.js.
Is It Possible to Combine Multiple .ts Files into a Single .js File?
Yes, it’s possible. While compiling add –outFILE [OutputJSFileName] option.
example
func.ts
class customer{
name:String;
constructor(name:String){
this.name= name;
}
}

 

func1.ts
class cust {
name:string;
Id:number;
add(Id:number);
add(name:string);
add(value:any){
}
}

 

 

tsc –outFile comman.js func1.ts func.ts

comman.js
var customer = (function () {
function customer(name) {
this.name = name; }
return customer;
}());
var cust = (function () {
function cust() {
}
cust.prototype.add = ffunction (value) {
}
return cust;
}
());

ats

AngularJS is incredibly productive once you have mastered it. Despite all of this, it doesn’t prevent us from seeing its weaknesses. AngularJS is not perfect, with some very difficult concepts to grasp, and traps hard to avoid.Most of all, the Web has changed since AngularJS was conceived. JavaScript has changed.
New frameworks have emerged, with great ideas, or better implementation.
We are not the kind of developers to tell you that you should use this tool instead of that one. We just happen to know some tools very well, and know what fits the project. AngularJS was one of those tools, allowing us to build well-tested web applications, and to build them fast. We also tried to bend it where it didn’t fit. Don’t blame us, it happens to the best of us.
Will Angular 2 be the tool we will use without hesitation in our future projects?
It’s hard to say right now, because the framework is really young and the ecosystem only just blooming.But Angular 2 has a lot of interesting points, and a vision that few other frameworks have.
It has been designed for the Web of tomorrow, with ECMAScript 6, Web Components and Mobile in mind. When it was first announced, I was, like many, sad at first that the 2.0 version would not be a simple update

Introduction to ECMA6

If you’re reading this, we can be pretty sure you have heard of JavaScript.

What we call JS is one implementation of a standard specification, called ECMAScript. The spec version you know the most about is the version 5, that has been used these last years.
But recently, a new version of the spec has been in the works, called ECMASCRIPT 6, ES6, or ECMASCRIPT 2015.
From now on, I’ll mainly say ES6, as it is the most popular way to reference it. It adds A LOT of things to JavaScript, like classes, constants, arrow functions, generators
It has so much stuff that we can’t go through all of it, as it would take the whole book. But Angular 2 has been
designed to take advantage of the brand new version of JavaScript. And, even if you can still use your old JavaScript, things will be more awesome if you use ES6
Grasping Angular’s philosophy
model
First and foremost, Angular 2 is component-oriented. You will write tiny components and, together,they will constitute a whole application. A component is a group of HTML elements in a template,dedicated to a particular task. For this, you will usually also need to have some logic linked to that template, to populate data, and react to events for example. For the veterans of AngularJS 1.x, it’s a bit like a ‘template/controller’ duo, or a directive.
Your components will be arranged in a hierarchical way, like the DOM is. A root component will have child components, each of them will also have children, etc…
angularcomp
If you want to display a pony race (who wouldn’t?), you’ll have something like an app (Ponyracer), with a child view (Race), displaying a menu (Menu), the logged in user (User), and, of course, the ponies (Pony) in the races:
Developing and building a Typescript app
Let’s start by creating our first Angular 2 app and our first component, with a minimum of tooling.You’ll have to install Node.js and NPM on your system. The best way to do that depends on your operating system – you can find more information on the official website. Make sure you have a recent enough version of Node.js (by executing node –version)
1. Then, create a new, empty folder for our experiment, and use tsc from that new empty folder to initialize a project. tsc stands for Typescript Compiler. It’s provided by the typescript NPM module we just installed globally:
tsc --init --target es5 --sourceMap --experimentalDecorators --
emitDecoratorMetadata
This will create a file, tsconfig.json, which stores the Typescriptt compilation options we are using Typescript with decorators (hence the last two flags), and we want our code to transpile to ECMASCRIPT 5, allowing it to run in every browser. The sourceMap option allows generating source maps, i.e. files that contain a mapping between the generated ES5 code and the original Typescript code. Those source maps are used by the browser to let you debug the ES5 code it
executes by stepping through the original Typescript code that you have written.
We now want to start using our preferred IDE. You can use pretty much anything you want, but you should activate the Typescript support for maximum comfort (and make sure you are using Typescript(1.5+). Pick your favorite IDE: Webstorm, Atom, VisualStudio Code… All of them have great support for Typescript.
The Typescript compiler (and usually the IDE) relies on the tsconfig.json file to know what options it should use. The file should look like the following:

{
“compilerOptions”: {
“target”: “es5”,
“module”: “system”,
“moduleResolution”: “node”,
“outDir”: “app/js”,
“sourceMap”: true,
“emitDecoratorMetadata”: true,
“experimentalDecorators”: true,
“removeComments”: false,
“noImplicitAny”: false
},
“exclude”: [
“node_modules”,

]
}

you might have the question what does this mean “outDir”: “app/js”
it is the default directory for all js files automatically after compilation of ts files
in case you dont have angular 2,its library and dependency use the following steps
2.For the Angular 2 library, we are going to download it using NPM, a great tool to manage dependencies.To avoid a few problems, we’ll use NPM version 3. Check which version you have with:
npm -v
If you don’t have NPM version 3, you can easily update NPM:
npm install -g npm
Now that’s done, let’s start by creating the package.json file, containing all the information that NPM needs
npm init
3.Then, let’s install Angular 2 and its dependencies.

npm install –save @angular/core @angular/compiler @angular/common
@angular/platform-browser @angular/platform-browser-dynamic rxjs@5.0.0-beta
.6 reflect-metadata zone.js

You can have a look at your package.json file, it should now contain the following dependencies:
• the different @angular packages.
• reflect-metadata, as we are using decorators.
• RxJS or Reactive Extensions for JavaScript is a library for transforming, composing, and querying streams of data. We mean all kinds of data too, from simple arrays of values, to series of events (unfortunate or otherwise), to complex flows of data.
•Typings are used by your editor to give you code hinting/intellisense, and es6-shim.min.js is a code that emulates ES6 features for ES5 browsers. Some of those features are Promise, Array.from()…
While your code is translated to ES5, you need to include es6-shim so you can use those new features in it… Consider this ES6 code:
let test1 = () => 123 + 456;
let test2 = new Promise((resolve, reject ) => {});
it will be translated to ES5 code:
var test1 = function () { return 123 + 456; };
var test2 = new Promise(function (resolve, reject) { });
but without es6-shim Promise would be undefined…
• and finally, the zone.js module, doing the heavy lifting of running our code in isolated zones for detecting the changes
package.json looks like this
{
  "name": "angular-2",
  "version": "1.0.0",
  "scripts": {
    "start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.13",
    "systemjs": "0.19.25",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.6"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.8.9",
    "typings":"^0.7.11"
  }
}

 

We execute most npm scripts in the following way: npm run followed by a script-name. Some commands (such as start) don’t require the run keyword. Here’s what these scripts do:

 

npm start – runs the compiler and a server at the same time, both in “watch mode”

npm run tsc – runs the TypeScript compiler once

npm run tsc:w – runs the TypeScript compiler in watch mode; the process keeps running, awaiting changes to TypeScript files and recompiling when it sees them

 

npm run lite – runs the lite-server, a light-weight, static file server with excellent support for Angular apps that use routing

 

npm run typings – runs the typings tool separately

 

npm run postinstall – called by npm automatically after it successfully completes package installation.

 

This script installs the TypeScript definition files defined intypings.json

 

 

4. Last thing to make the compiler happy, you have to install the typings for the things related to ES6. The easiest way is to install the typings for core-js:

 

typings init
typings install –save –global dt~core-js
And add the typings to the exclude section of the tsconfig.json file:

 

“exclude”: [
“node_modules”,
“typings/main.d.ts”,
“typings/main”
]
5Enabling the TypeScript Compiler
in order to develop code in TypeScript using the PHPStorm or the WebStorm IDE we should perform following steps
In the Default Preferences setting window, enable the TypeScript compiler, specifying the node interpreter and specify the main file we want to compile

 

Screenshot from 2016-07-04 10:59:12
6 Our First Component
component: components are the main way by which we build and specify elements and logic

 

Every Angular app has at least one root component, conventionally named AppComponent, that hosts the client user experience. Components are the basic building blocks of Angular applications.
app is the root folder inside it create two folder one is for js files and one for ts files
app/app.component.ts
import {Component} from "angular2/core";
import {NameService} from "./nameservice";

@Component({
    selector: 'my-app',
    templateUrl: 'app/ts/namelist.component.html',
    Inputs: ['newnames']
})


export class AppComponent {

    newitems:Array;

    constructor(nameservice:NameService) {
        this.newitems = nameservice.getNames();


    }
    
}

Our component has four parts
selector:defines the name of the HTML tag where this component will live. In this case, our component will by shown through the <my-app></my-app> tags

you can see that tag in index.html
templateurl:defines the url of our template
Inputs:input that we want to sent to our template url
component class: that controls the appearance and behavior of a view through its template.
7nameservice.ts file

import {Json} from "angular2/src/facade/lang";
export class NameService {
    items:Array;

    constructor() {
        this.items = [
            {name: 'Christoph Burgdorf', degree: 'mca'},
            {name: 'Pascal Precht', degree: 'mca'},
            {name: 'thoughtram', degree: 'mca'},
            {name: 'anubhav', degree: 'mca'},
            {name: 'deepak', degree: 'mca'},
            {name: 'akshay', degree: 'mca'}
        ];
    }

    getNames() {
        return this.items
    }


}

this file simply return a array of items appcomponent inject this service and get this data and transefer it to the templateurl
8•add main.ts file

import {bootstrap}    from 'angular2/platform/browser';
import {AppComponent} from './app.component';
import {NameService} from "./nameservice";

bootstrap(AppComponent, [NameService]);

Here bootstrap is same as that of ng-app in angular1 and used to bootsrap our application
and inject the nameService

9add namelist.component.html

<h1 style="text-align:center;color:red!important;">DATA OF STUDENTS</h1>
<table class="table table-bordered" style="border:2px solid blue">
    <thead>
    <tr style="border:2px solid red">
        <td style="border:2px solid red">name</td>
        <td style="border:2px solid red">degree</td>
    </tr>
    </thead>
    <tr *ngFor="#i of newitems" style="border:2px solid red">
        <td style="border:2px solid red">{{i.name}}</td>
        <td style="border:2px solid red">{{i.degree}}</td>
    </tr>
</table>
<button type="button" class="btn btn-primary" (click)="goToAboutPage">
add more students</button>
10add  index.html
<!DOCTYPE html>Angular 2 QuickStart
     <!-- Load libraries (Note: IE required polyfills, in this exact order
_ -->
    http://node_modules/es6-shim/es6-shim.min.jshttp://node_modules/systemjs/dist/system-polyfills.jshttp://node_modules/angular2/es6/dev/src/testing/shims_for_IE.jshttp://node_modules/angular2/bundles/angular2-polyfills.jshttp://node_modules/systemjs/dist/system.src.jshttp://node_modules/rxjs/bundles/Rx.jshttp://node_modules/angular2/bundles/angular2.dev.jshttp://node_modules/angular2/bundles/router.dev.js
    <!-- Configure SystemJS -->
<script>
System.config({ packages: { app: { format: 'register', defaultExtension: 
'js' } } }); 
System.import('app/js/main').then(null, console.error.bind(console)); 
</script>
</head>
<body>
<div class="container-fluid>
<my-app>Loading--</my-app>
 you might be wondering what these lines do
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
       here default extension for file is given as js so that import 
{AppComponent} from './app.component'  does not require js extension
and then  System.import('app/js/main').then(null, console.error.bind(console));
here we are specifying our app main module main.js file

10.run the application
11.type the command
npm start


Note:When you issue the com­mand npm start from the root direc­tory of your nodejs project, node will look for
 a scripts object in your package.json file. If found, it will look for a script with the key start and run the com
mand spec­i­fied as its value.in case their is no start script it will look for server.js 

in case you feel any problem you can clone project from given link

Knoldus have organized a half an hour session on 8 Jul 2016 at 4:40 PM. The topic was Introduction to Typescript.
Here is the video of the live session
This entry was posted in AngularJs2.0. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s