Typescript Practice - Exercises 1. Enumerator: Pricelist (

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Typescript Practice - Exercises

1. Enumerator
​enum​ PriceList{
"$23.50"​ ​=​ ​1​,
"$11.00"​,
"$36.99"​,
}

var​ book1 ​=​ ​"TypeScript in Plain Language"​;

console.log(book1 ​+​ ​" costs "​ +


​ ​ PriceList[​2​]);

2. Types

var x = 3;
var y = 0;
var z = "Tony";
var a;
console.log(" x = 3: " + Boolean(x));
console.log(" x = 3 !x:" + Boolean(!x));
console.log(" y = 0: " + Boolean(y));
console.log(" z = Tony " + Boolean(z));
console.log(" z = Tony !z:" + Boolean(!z));
console.log("a " + Boolean(a));
console.log("a !a: " + Boolean(!a));

3. Functions
​export
function conversion(x:number,y:string="f"):void{
if(y === "f"){
console.log((x-32) * 5 / 9 + " Celsius");
}
else if(y === "c"){
console.log((x * 9 / 5 + 32) + " Fahrenheit");
}
else{
console.log("Sorry, this conversion is not supported");
}
}
conversion(100,"c");

4. ​Class

export
class Automobile{
make:string;
model:string;
color:string;
mileage:number;
rating:number;
constructor(myMake:string, myModel:string, myColor:string, myMileage:number,
myRating:number){
this.make = myMake;
this.model = myModel;
this.color = myColor;
this.mileage = myMileage;
this.rating = myRating;
}

var honda = new Automobile("honda", "Outback", "blue", 67000, 9);

for (let item in honda){


console.log(item + ": " + honda[item]);
}

5. Iterators & Generators

let​ someArray = [​1​, ​"string"​, ​false​];

for​ (​let​ entry of someArray) {


​console​.log(entry); ​// 1, "string", false
}
Both ​for..of​ and ​for..in​ statements iterate over lists; the values
iterated on are different though, ​for..in​ returns a list of ​keys​ on the
object being iterated, whereas ​for..of​ returns a list of ​values​ of the
numeric properties of the object being iterated.

let list = [4, 5, 6];

for (let i in list) {


​console​.log(i); ​// "0", "1", "2",
}

for (let i of list) {


​console​.log(i); ​// "4", "5", "6"
}

Another distinction is that ​for..in​ operates on any object; it serves


as a way to inspect properties on this object.​for..of​ on the other
hand, is mainly interested in values of iterable objects. Built-in
objects like ​Map​ and ​Set ​implement ​Symbol.iterator​ property allowing
access to stored values.

let​ pets = ​new​ Set([​"Cat"​, ​"Dog"​, ​"Hamster"​]);


pets[​"species"​] = ​"mammals"​;

for​ (​let​ pet ​in​ pets) {


​console​.log(pet); ​// "species"
}

for​ (​let​ pet of pets) {


​console​.log(pet); ​// "Cat", "Dog", "Hamster"
}
6.
class Test{
public color:string;
private _intensity:number;

get intensity():number{
return this._intensity;
}

set intensity(x:number){
this._intensity = x;
}
}

var xyz = new Test();

xyz.color = "blue";
xyz.intensity = 8;

console.log(xyz.intensity);

You might also like