(1) Learn typescript

Time:2020-8-2

Typescript
Typescript tutorial

Basic grammar

Typescript reserved keywords

break as catch switch case if
throw else var number string get
module type instanceof typeof public private
enum export finally for while void
null super this new in return
true false any extends static let
package implements interface function new try
yield const continue do

Typescript supports two types of comments

  • Single line comment (/ /) – the text after / / is the comment content.
  • Multiline comments (/ * * /) – these comments can span multiple lines.

Typescript and object oriented

Typescript is an object-oriented programming language.

  • objectAn object is an instance of a class that has state and behavior.
  • classA class is a template that describes the behavior and state of a class of objects.
  • methodMethod is the implementation step of the operation of a class.

Typescript object oriented programming example:

class  Site  {  
   name():void  {
    console.log("Runoob")
   }  
}  
var  obj = new  Site();
obj.name();

Foundation type

Any type

Let X: any = 1; // numeric type
X ='I am who I am '; // string type
X = false; // boolean type

Number type

Let binaryliteral: number = 0b1010; // binary
Let octalliteral: number = 0o744; // octal
Let decliteral: number = 6; // decimal
Let hexliteral: number = 0xf00d; // hex

String type

let name: string = "Runoob";
let years: number = 5;
Let words: String ='Hello, this year is the anniversary of ${name} releasing ${years + 1} ';

boolean type

let flag: boolean = true;

Array type

//Add [] after element type
let arr: number[] = [1, 2];

//Or use array generics
let arr: Array<number> = [1, 2];

tuple

let x: [string, number];
X = ['runoob ', 1]; // normal operation
X = [1, 'runoob']; // error reported
console.log (x [0]); // output runoob

enumeration

enum Color {Red, Green, Blue};
let c: Color = Color.Blue;
console.log (c) ; // output 2

void

function hello(): void {
    alert("Hello Runoob");
}

null

undefined

//Enable -- strictnullchecks
let x: number;
X = 1; // runs correctly
X = undefined; // running error
X = null; // running error
//Enable -- strictnullchecks
let x: number | null | undefined;
X = 1; // runs correctly
X = undefined; // runs correctly
X = null; // runs correctly

Never type

let x: never;
let y: number;

//Running error, numeric type cannot be converted to never type
x = 123;

//Run correctly, never type can be assigned to never type
x = (()=>{ throw new Error('exception')})();

//Run correctly, never type can be assigned to numeric type
y = (()=>{ throw new Error('exception')})();

//A function with a return value of never can be a case of throwing an exception
function error(message: string): never {
    throw new Error(message);
}

//A function with a return value of never can be a termination point that cannot be executed
function loop(): never {
    while (true) {}~~~~
}

Typescript variable declaration

Variable declaration

Naming rules for typescript variables:

  • Variable names can contain numbers and letters
  • Except for the underline_ Except for the U.S. dollar sign and the dollar dollar sign, no other special characters, including spaces, can be included
  • Variable name cannot start with a number
varuname:string\="Runoob";  
varscore1:number\=50;  
varscore2:number\=42.50  
varsum\=score1+score2  
console.log ("first name) + uname"  
console.log ("first subject score: + Score1)"  
console.log ("second subject score: + score2)"  
console.log ("total score: + sum)

Execute the code and the output result is as follows:

Name: runoob
First subject score: 50
Grade of the second subject: 42.5
Total score: 92.5

Type Asserts

var  str = '1'  var  str2:number = <number> <any> str 
//STR and STR2 are string types console.log (str2)

Type inference

Var num = 2; // type inferred as number  
console.log (the value of "num variable is" + Num); 
Num = "12"; // compilation error  
console.log(num);

Variable scope

Typescript has the following scopes:

  • global scopeGlobal variables are defined outside the program structure and can be used anywhere in your code
  • Class scope– this variable can also be calledfield。 Class variables are declared inside a class, but outside the class’s methods. This variable can be accessed through the object of the class. Class variables can also be static, static variables can be directly accessed through the class name
  • Local scope– a local variable, which can only be used in a code block (such as a method) in which it is declared
var  global_ Num = 12 // global variables
class  Numbers  {  
num_ Val = 13; // instance variable
Static sval = 10; // static variable

storeNum():void  {  
    var  local_ Num = 14; // local variable  
    }  
    
}
console.log ("the global variable is: + global_ num)
console.log ( Numbers.sval )// static variables
var  obj = new  Numbers();
console.log (instance variable:+ obj.num_ val)

Execute the above code, and the output result is as follows:

The global variable is: 12
10
Instance variable: 13

operator

Typescript mainly includes the following operations:

  • Arithmetic operator
  • Logical operator
  • Relational operators
  • Bitwise Operators
  • Assignment Operators
  • Ternary / conditional operators
  • String operator
  • Class Operators

Arithmetic operator

varnum1:number=10  
varnum2:number=2  
varres:number=0  
  
res=num1+num2  
console.log ("add:" RES);  
  
res=num1-num2;  
console.log ("minus:" RES)  
  
res=num1*num2  
console.log ("multiply:" RES)  
  
res=num1/num2  
console.log ("division:" RES)  
  
res=num1%num2  
console.log ("remainder:" RES)  
  
num1++  
console.log ("num1 increment operation: + num1)  
  
num2--  
console.log ("num2 auto subtract operation: + num2)

Execute the above code, and the output result is as follows:

Add: 12
Less: 8
Multiply: 20
Except: 5
Remainder: 0
Num1 increment: 11
Num2 auto subtraction: 1

Relational operators

var  num1:number = 5;
var  num2:number = 9;

console.log (the value of num1 is: "num1)";
console.log ("num2 is the value of" + num2) ";

var  res = num1>num2
console.log ("num1 greater than n num2:" + RES)

res = num1<num2
console.log ("num1 less than num2:" + RES)

res = num1>=num2
console.log ("num1 greater than or equal to num2:" + RES)

res = num1<=num2
console.log ("num1 less than or equal to num2:" + RES)

res = num1==num2
console.log ("num1 equals num2:" + RES)

res = num1!=num2
console.log ("num1 is not equal to num2:" + RES)

Execute the above code, and the output result is as follows:

The value of num1 is: 5
The value of num2 is: 9
Num1 is greater than n num2: false
Num1 less than num2: true
Num1 greater than or equal to num2: false
Num1 is less than or equal to num2: true
Num1 equals num2: false
Num1 is not equal to num2: true

Logical operator

var  avg:number = 20;
var  percentage:number = 90;
console.log ("AVG value is) + AVG +", percentage value is: "percentage");
var  res:boolean = ((avg>50)&&(percentage>80));
console.log("(avg>50)&&(percentage>80): ",res);
var  res:boolean = ((avg>50)||(percentage>80));
console.log("(avg>50)||(percentage>80): ",res);
var  res:boolean=!((avg>50)&&(percentage>80));
console.log("!((avg>50)&&(percentage>80)): ",res);

Execute the above code, and the output result is as follows:

AVG value: 20, percentage value: 90
(avg>50)&&(percentage>80):  false
(avg>50)||(percentage>80):  true
!((avg>50)&&(percentage>80)):  true

Bitwise Operators

Var a: number = 2; // binary 10 
Var B: number = 3; // binary 11  

var  result; result = (a & b);
console.log("(a & b) => ",result)  

result = (a | b);
console.log("(a | b) => ",result)

result = (a ^ b);
console.log("(a ^ b) => ",result);

result = (~b);
console.log("(~b) => ",result);

result = (a << b);
console.log("(a << b) => ",result);

result = (a >> b);
console.log("(a >> b) => ",result);

result = (a >>> 1);
console.log("(a >>> 1) => ",result);

Execute the above code, and the output result is as follows:

(a & b) =>  2
(a | b) =>  3
(a ^ b) =>  1
(~b) =>  -4
(a << b) =>  16
(a >> b) =>  0
(a >>> 1) =>  1

Assignment Operators

var  a: number = 12
var  b:number = 10

a = b
console.log("a = b: "+a)

a += b
console.log("a+=b: "+a)

a -= b
console.log("a-=b: "+a)

a *= b
console.log("a\*=b: "+a)

a /= b
console.log("a/=b: "+a)

a %= b
console.log("a%=b: "+a)

Execute the above code, and the output result is as follows:

a = b: 10
a+=b: 20
a-=b: 10
a*=b: 100
a/=b: 10
a%=b: 0

Ternary operator

var  num:number = -2
Var result = num > 0? "Greater than 0": "less than 0, or equal to 0"
console.log(result)

Execute the above code, and the output result is as follows:

Less than or equal to 0

Class Operators

var  num = 12
console.log (typeof Num); // output result: number

Execute the above code, and the output result is as follows:

number

Other Operators

var  x:number = 4
var  y = -x;
console.log ("x value is: ', x); // output result 4 
console.log ("y value is:" Y); // output result - 4

Execute the above code, and the output result is as follows:

The value of X is 4
The y value is: - 4

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]