Posted on Thursday, January 10, 2019
Intro:
-it is a superset of javascript
How it works:
-it is compiled into clean and simple javascript.
Benefits:
-it leverages the knowledge of object oriented programming (C#, Java)
File:
-typescript file extension is .ts
-For an example, example1.ts
How to compile:
-tsc filename.ts
-For an example, tsc example1.ts
-A new file will be created with javascript extension
i.e. example1.js
How to use:
-use example1.js [not example1.ts] in your html code
-Browser doesn't support .ts
This is the simple app i have created which can be viewed here: Hobbies List
In the following code, I have created a class called Hobby with two string properties name and year. It also includes a constructor accepting two parameters to initialise those properties.
After this, there is two variable; hobby is a Hobby and hobbies is an array of Hobby. Similary, there are two functions addHobby() and listHobby() which returns nothing. The first function initialise the hobby variable and push into the hobbies array.
The listHobby() helps to select the html element (ol) and then create <li> element and append it to the <ol> element.
class Hobby{
name:string;
year:number;
constructor(name:string,year:number){
this.name=name;
this.year=year;
}
}
let hobby:Hobby;
let hobbies:Array=[];
function addHobby(name:string,year:number):void{
hobby=new Hobby(name,year);
hobbies.push(hobby);
console.log(name+ " " + year + "successfully stored.");
listHobby();
}
function listHobby():void{
document.getElementById("myList").innerHTML="";
for(let hobby of hobbies){
let list=document.createElement("li");
list.innerHTML=hobby.name + " : "+ hobby.year;
document.getElementById("myList").appendChild(list);
}
}
This .ts file will compile into following .js file.
var Hobby = /** @class */ (function () {
function Hobby(name, year) {
this.name = name;
this.year = year;
}
return Hobby;
}());
var hobby;
var hobbies = [];
function addHobby(name, year) {
hobby = new Hobby(name, year);
hobbies.push(hobby);
console.log(name + " " + year + "successfully stored.");
listHobby();
}
function listHobby() {
document.getElementById("myList").innerHTML = "";
for (var _i = 0, hobbies_1 = hobbies; _i < hobbies_1.length; _i++) {
var hobby_1 = hobbies_1[_i];
var list = document.createElement("li");
list.innerHTML = hobby_1.name + " : " + hobby_1.year;
document.getElementById("myList").appendChild(list);
}
}