> npm i typescript
> tsc test.ts
> node test.js
Type System
- any: no type
- number: double precision (64-bit) floating point
- null vs. undefined: A variable initialized with undefined means that the variable has no value or object assigned to it while null means that the variable has been set to an object whose value is undefined.
Variable Declaration
var name:string = "John";
var score1:number = 50;
var score2:number = 42.50
var sum = score1 + score2
console.log("name"+name)
console.log("first score: "+score1)
console.log("second score: "+score2)
console.log("sum of the scores: "+sum)
Type Assertion
changing a variable from one type to another
var str = 1;
var str2:number = <number> str //str is now of type number
typeof operator
var num = 12 console.log(typeof num); //output: number
If statement
var num:number = 5
if (num > 0) {
console.log("number is positive")
} else if(num < 0) {
console.log(num+" is negative")
} else {
console.log("non-neg nor pos");
}
Switch statement
Unless you put a break after each block of code, execution flows into the next block.
var grade:string = "A";
switch(grade) {
case "A": {
console.log("Excellent");
break;
}
case "B": {
console.log("Good");
break;
}
case "C": {
console.log("Fair");
break;
}
case "D": {
console.log("Poor");
break;
}
default: {
console.log("Invalid choice");
break;
}
}
for loop
var num:number = 5;
var i:number;
var factorial = 1;
for(i = num;i>=1;i--) {
factorial *= i;
}
for-in loop
var j:any;
var n:any = "a b c"
for(j in n) {
console.log(n[j])
}
while loop
var num:number = 5;
var factorial:number = 1;
while(num >=1) {
factorial = factorial * num;
if(num == 3){
break;
}
if(num == 4){
continue;
}
num--;
}
do while loop
var n:number = 10;
do {
console.log(n);
n--;
} while(n>=0);
Function
function greet():string { //the function returns a string
return "Hello World"
}
- func param without specifying type is considered 'any'
optional param
The last param of a function can be set as optional by adding '?' after the param name.
If an optional parameter is not passed a value during the function call, the parameter’s value is set to undefined.
function disp_details(id:number,name:string,mail_id?:string) {
console.log("ID:", id);
console.log("Name",name);
if(mail_id!=undefined)
console.log("Email Id",mail_id);
}
rest param
rest parameters act as placeholders for multiple arguments of the same type.
- this is always the last param
- this is always of type: array
- there should only be 1 rest param
function addNumbers(a,b,...nums:number[]) {
** the '...' is part of the syntax
default param value
function calculate_discount(price:number,rate:number = 0.50) {
...
}
- if rate argument provided, it will overwrite the default
- Otherwise the rate will be 0.5
function as variable
var func = function(a:number,b:number) { ... }
recursive anonymous function
(function () {
var x = "Hello!!";
console.log(x)
})()
- 在decl的最后用一对括号自己调用自己
prototype
add method or properties to an object.
function employee(id:number,name:string) {
this.id = id
this.name = name
}
var emp = new employee(123,"Smith")
// adding email property to employee object
employee.prototype.email="smith@abc.com"
Overloading
Lambda
Used for declaring anonymous functions
Syntax
-
Parameters − A function may optionally have parameters
-
=> − It is also called fat arrow
-
Statements − represent the function’s instruction set
Example
var foo = (x:number)=> {
x = 10 + x
console.log(x)
}
foo(100)
Number
The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects.
var var_name = new Number(value)
- Non numeric number returns NaN
property
method
String
constructor
var var_name = new String(string);
length
string.length
methods
Array
- Array cannot be resized
- Array is declared with var
array literal
var array_name[:datatype]; //declaration
array_name = [val1,val2,valn..] //initialization
- multidimensional
var multi:number[][] = [[1,2,3],[23,24,25]]
array object
var arr_names:number[] = new Array(4)
// OR
var names:string[] = new Array("Mary","Tom","Jack","Jill")
access element
array_name[subscript] = value
traverse
- for ... in
var j:any;
var nums:number[] = [1001,1002,1003,1004]
for(j in nums) {
console.log(nums[j])
}
method
Tuple
tuples enable storing multiple fields of different types
var mytuple = [10,"Hello"];
mytuple[0] = 20;
console.log(mytuple[1]);
properties & methods
mytuple.length //大小
mytuple.push(12) //加入新元素
mytuple.pop() //删除最后元素
mytuple[i] = val //修改元素i的值
Union Types
The variable can take one of the the types indicated in the union types
- a sequence of types separated by vertical bars.
- i.e. Type1|Type2|Type3
var val:string|number
val = 12 // OR
val = 'yo mama'
- val can be string or number
function disp(name:string|string[]) {
- function disp can take string or string arrays as args
var arr:number[]|string[];
- array can be numeric array or string array -- NOT a combination of both
Interface
an interface declares the syntax that any entity must adhere to.
- Interface declares but does not define --
- properties
- methods
- events
- These are later defined by the deriving class
Syntax
interface interface_name {
}
Example
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
- create a class for iPerson
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
inheritance
interface Musician extends IPerson {
instrument:string
}
Class
-
Fields − A field is any variable declared in a class. Fields represent data pertaining to objects
-
Constructors − Responsible for allocating memory for the objects of the class
-
Functions − Functions represent actions an object can take. They are also at times
class Car {
//field
engine:string;
//constructor
constructor(engine:string) {
this.engine = engine
}
//function
disp():void {
console.log("Engine is : "+this.engine)
}
}
this
The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword.
static
- Static can be both applied to variable and function
class StaticMem {
static num:number;
static disp():void {
console.log("The value of num is"+ StaticMem.num)
}
}
Access Specifier
instance
var object_name = new class_name([ arguments ])
inheritance
- between classes
class Shape {
Area:number
constructor(a:number) {
this.Area = a
}
}
class Circle extends Shape {
disp():void {
console.log("Area of the circle: "+this.Area)
}
}
var obj = new Circle(223);
obj.disp()
- multi-level inheritance
class Root {
str:string;
}
class Child extends Root {}
class Leaf extends Child {} //indirectly inherits from Root by virtue of inheritance
implement
interface ILoan {
interest:number
}
class AgriLoan implements ILoan { ... }
Override
child class redefines the superclass’s method.
class ChildClass extends SuperClass {
method():void {
super.method() // call superclass implementation
console.log("method() is printing a string…")
}
}
- super.method() calls the super class method from child class
instanceof
returns true if the object belongs to the specified type.
obj instanceof Class;
Object
var object_name = {
key1: “value1”, //scalar value
key2: “value”,
key3: function() {
//functions
},
key4:[“content1”, “content2”] //collection
};