The first way to learn TypeScript: installation, basic type, variable declaration, operator and conditional statement

1: Install TypeScript

There are two main ways to get TypeScript tools:

  • Through npm (Node.js package manager)
  • Install TypeScript plug-in for Visual Studio

For users using npm:

> npm install -g typescript

For Visual Studio users

1, Download Visual Studio Code.

2: click the code file edited in the current period in the left window, and select open in command prompt

 

2: TypeScript base type

Type classification:

Variables of any type declared as any can be given any type of value any

Number type it can be used to represent integers and fractions. let binaryLiteral: number = 6; / / binary

String type let name: string = "Runoob"; a character series, using single quotation marks (') or double quotation marks (") to represent the string type. Backquotes (`) to define multiline text and inline expressions.

Boolean type indicates logical values: true and false let flag: boolean = true

Array type declares the variable as an array.

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

/ / or use array generic let arr: array < number > = [1, 2];

Tuple tuple type is used to represent an array of known element quantity and type. The type of each element does not have to be the same, and the type of corresponding position needs to be the same.

                                  let x: [string, number];

x = ['Runoob', 1]; / / normal operation

x = [1, 'Runoob']; / / error reported

console.log(x[0]); / / output Runoob

Enumeration enumeration types are used to define a collection of values.

                  enum Color {Red, Green, Blue};

                  let c: Color = Color.Blue;

                  console.log(c); / / output 2

null means the object value is missing.

Undefined is used to initialize a variable to an undefined value

Never never is a subtype of other types, including null and undefined, representing values that never appear.

void is used to identify the type of return value of a method, indicating that the method has no return value.

                  function hello(): void {
   
                  alert("Hello Runoob");
             
               }
 Null and Undefined
null

//null means "nothing" in JavaScript.

null Is a special type with only one value. Represents an empty object reference.

//Use typeof to detect that null return is object.
undefined

//In JavaScript, undefined is a variable with no value set.

typeof A variable with no value will return undefined. 

Null and Undefined Is any other type (including void)The sub type of can be assigned to other types, such as number type. In this case, the assigned type will become null or undefined. While in TypeScript Enable strict null verification in(--strictNullChecks)Features that enable null and undefined Can only be assigned to void Or the corresponding type. The example code is as follows:

// Enable -- strictNullChecks
let x: number;
x = 1; // Run correctly
x = undefined;    // Operation error
x = null;    // Operation error

//In the above example, the variable x can only be of number type. If a type may appear null or undefined, you can use | to support multiple types. The example code is as follows:

// Enable -- strictNullChecks
let x: number | null | undefined;
x = 1; // Run correctly
x = undefined;    // Run correctly
x = null;    // Run correctly
 never type

never Other types (including null and undefined)Represents a value that never appears. This means that the statement is never Variables of type can only be never Type, which is usually expressed as throwing an exception or unable to execute to the termination point (such as infinite loop) in the function. The example code is as follows:

let x: never;
let y: number;

// Operation error, number type cannot be changed to never type
x = 123;

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

// Correct operation, the never type can be assigned to the number type
y = (()=>{ throw new Error('exception')})();

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

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

3: TypeScript variable declaration

    

var uname = "Runoob";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("Name: " + uname);
console.log("First subject score: " + score1);
console.log("Second subject score: " + score2);
console.log("Total score: " + sum);


//Name: Runoob
//First subject score: 50
//Second subject score: 42.5
//Total score: 92.5

Variable scope

The variable scope specifies the location of the variable definition.

The availability of variables in a program is determined by the scope of the variables.

TypeScript has the following scopes:

  • Global scope − global variables are defined outside the program structure and can be used anywhere in your code.

  • Class scope − this variable can also be called a field. Class variables are declared in a class, but outside the methods of the class. This variable can be accessed through the object of the class. Class variables can also be static. Static variables can be accessed directly through the class name.

  • Local scope − local variable, local variable can only be declared in one code block

   

var global_num = 12; // global variable
var Numbers = /** @class */ (function () {
    function Numbers() {
        this.num_val = 13; // Class variables
    }
    Numbers.prototype.storeNum = function () {
        var local_num = 14; // local variable
    };
    Numbers.sval = 10; // Static variables
    return Numbers;
}());
console.log("The global variable is: " + global_num);
console.log(Numbers.sval); // Static variables
var obj = new Numbers();
console.log("Class variables: " + obj.num_val);


//The global variable is: 12
10
//Class variable: 13

 

4:TypeScript operator

Arithmetic operator

var num1:number = 10
var num2:number = 2
var res:number = 0
   
res = num1 + num2
console.log("plus:        "+res);

res = num1 - num2;
console.log("reduce: "+res)

res = num1*num2
console.log("ride:    "+res)

res = num1/num2
console.log("except:   "+res)
   
res = num1%num2
console.log("Remainder:   "+res)

num1++
console.log("num1 Self increment operation: "+num1)

num2--
console.log("num2 Self decrement operation: "+num2)

//Add: 12
//Minus: 8
//Ride: 20
//Except: 5
//Remainder: 0
num1 Self increment operation: 11
num2 Self decrement operation: 1
Relational operators
 
var num1:number = 5;
var num2:number = 9;
 
console.log("num1 The value is: "+num1); 
console.log("num2 The value is:"+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 Be equal to num2: "+res)  
 
res = num1!=num2  
console.log("num1 Not equal to num2: "+res)


num1 The value is: 5
num2 The value is:9
num1 greater than n num2: false
num1 less than num2: true
num1 Greater than or equal to  num2: false
num1 Less than or equal to num2: true
num1 Be equal to num2: false
num1 Not equal to num2: true

 

Logical operators

var avg:number = 20; 
var percentage:number = 90; 
 
console.log("avg The value is: "+avg+" ,percentage The 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);


avg The value is: 20 ,percentage The value is: 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);


(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)


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)


Less than or equal to 0
Class Operators 

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


//Other Operators 

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


x The value is:  4
y The value is:  -4


//String operators: join operator (+)

var msg:string = "RUNOOB"+".COM" 
console.log(msg)


RUNOOB.COM

TypeScript conditional statement

   

  • If statement - use this statement to execute code only if the specified condition is true
  • if...else statement - executes code when the condition is true, and other code when the condition is false
  • if...else if....else statement - use this statement to select one of multiple code blocks to execute
  • switch statement - use this statement to select one of multiple code blocks to execute

 

                 if

var  num:number = 5
if (num > 0) { 
   console.log("Number is positive") 



//Number is positive



                if-else


var num:number = 12; 
if (num % 2==0) { 
    console.log("Even numbers"); 
} else {
    console.log("Odd number"); 
}

//Even numbers



                 if...else if....else Sentence

var num:number = 2 
if(num > 0) { 
    console.log(num+" Positive number") 
} else if(num < 0) { 
    console.log(num+" It is negative.") 
} else { 
    console.log(num+" It's not a positive number, it's not a negative number") 
}

2 Positive number



                switch...case 



var grade:string = "A"; 
switch(grade) { 
    case "A": { 
        console.log("excellent"); 
        break; 
    } 
    case "B": { 
        console.log("good"); 
        break; 
    } 
    case "C": {
        console.log("pass"); 
        break;    
    } 
    case "D": { 
        console.log("Fail,"); 
        break; 
    }  
    default: { 
        console.log("illegal input"); 
        break;              
    } 
}

//excellent
















 

99 original articles published, 40 praised, 90000 visitors+
Private letter follow

Tags: TypeScript less npm Javascript

Posted on Mon, 13 Jan 2020 02:46:11 -0800 by musicdirector