24 April 2020

TypeScript Fundamentals (Plural Sight) 25/09/2018

Typescript is supported by any browser, any OS, opensource and have tool support.
Key features of typescript is that It provides static typing, encapsulation through classes and modules, support constructors, properties, functions, define interfaces, intellisense and syntax checking.


test1.ts
 
 
class Greeting {
Greet : string;
constructor(greeting : string) {
this.Greet = greeting;
}
greetMethod() : string {
return this.Greet + "Greeting Message";
}
}
 
 
from command prompt run
tsc test1.ts // it will generate test1.js in the same directory
tsc -outFile test1Out.js test1.ts // it will generate test1Out.js file after compiling test1.ts file. tsc meaning typescript compiler.



To Practice typescript we can use online typescript 
playground: http://www.typescriptlang.org/play/



Primitive types
 
var age : number = 2;
 
var score : number = 98.25;
 
var hasData : boolean = true;
 
var firstName : string = 'john';
 
var names : string[] = ['john', 'dan', 'aaron'];
 
var firstPerson : string = names[0];
 
Null type is subtype of all primitives (except void and undefined), so we can set null to any datatype as below:
var num : number  = null;
var str : string = null;
var isHappy : boolean = null;
var customer : { } = null;
 
var age : number;  // value is undefined
var madhu = undefind // meaning madhu is set to any type and value is undefined.


Object Types



Ex 1:
var square = { h : 20, w : 20 };
var line : Object = { x : 10, y : 20 }; // here we explicitly specifying line is an object.
 
 
Functions:
var multiply = function(x : number) {
return x*x;
};
 
 
Functions Ex 2:
var myFunc = function( h: number , w : number) {
return h*w;
};
 
 
We can rewrite as below:
var myFunc = (h : number, w : number) => h*w;  // function keyword got omitted and => is compact return statement.

No comments:

Post a Comment