TypeScript study notes 01

01. Introduction

TypeScript is a superset of JavaScript that supports the ECMAScript 6 standard (ES6 tutorial).

TypeScript is a free and open source programming language developed by Microsoft.

The design goal of TypeScript is to develop large-scale applications, which can be compiled into pure JavaScript, and the compiled JavaScript can run on any browser.

TypeScript object-oriented programming example:

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

The above example defines a class Site, which has a method name(), which outputs the string Runoob on the terminal.
 

The new keyword creates an object of the class which calls the method name().

The JavaScript code generated after compilation is as follows:

var Site = /** @class */ (function () {
    function Site() {
    }
    Site.prototype.name = function () {
        console.log("Runoob");
    };
    return Site;
}());
var obj = new Site();
obj.name();

02. TypeScript basic types

Contains the following categories

Any type    any A     variable declared as any can be assigned a value of any type.

    A double-precision 64-bit floating-point value of type     number . It can be used to represent integers and fractions.


let binaryLiteral: number = 0b1010; // 二进制
let octalLiteral: number = 0o744;    // 八进制
let decLiteral: number = 6;    // 十进制
let hexLiteral: number = 0xf00d;    // 十六进制

String type    string      A series of characters, use single quotes (') or double quotes (") to indicate the string type. Backticks (`) to define multi-line text and embedded expressions.

let name: string = "Runoob";
let years: number = 5;
let words: string = `您好,今年是 ${ name } 发布 ${ years + 1} 周年`;

The Boolean type    boolean    represents logical values: true and false.
 

let flag: boolean = true;

The array type    array    declares a variable as an array.

// 在元素类型后面加上[]
let arr: number[] = [1, 2];

// 或者使用数组泛型
let arr: Array<number> = [1, 2];

Tuple The tuple type is used to represent an array with a known number and type of elements. The types of each element do not have to be the same, and the types of the corresponding positions need to be the same.
 


let x: [string, number];
x = ['Runoob', 1];    // 运行正常
x = [1, 'Runoob'];    // 报错
console.log(x[0]);    // 输出 Runoob

Enumeration     enum      enumeration type is used to define a collection of values


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

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


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

null     null     indicates that the object value is missing.
 

undefined    undefined    is used to initialize variables to an undefined value

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

03.TypeScript variable declaration

Naming rules for TypeScript variables:
 

Variable names can contain numbers and letters.

Except for the underscore _ and the dollar $ sign, no other special characters, including spaces, are allowed.

Variable names cannot start with a number.

Declare the type and initial value of the variable:


var [variable name] : [type] = value;

For example:

var uname:string = "Runoob";

04. Type Assertion


Type assertions can be used to manually specify the type of a value, allowing variables to change from one type to another.
 


<类型>值

或:


值 as 类型
var str = '1' 
var str2:number = <number> <any> str   //str、str2 是 string 类型
console.log(str2)

05. Type inference

The TypeScript compiler utilizes type inference to infer the type when the type is not given.

If the type cannot be inferred due to lack of declaration, then its type is taken to be the default dynamic any type.

var num = 2;    // 类型推断为 number
console.log("num 变量的值为 "+num); 
num = "12";    // 编译错误
console.log(num);

The first line of code declares the variable num and = sets the initial value to 2. Note that variable declarations do not specify types. Therefore, the program uses type inference to determine the data type of the variable, the first assignment is 2, and num is set to the number type.

The third line of code, when we set the value of the string type for the variable again, the compilation will be wrong. Because the variable has been set to the number type.

06. Variable scope

Variable scope specifies where a variable is defined.

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

TypeScript has the following scopes:
 

Global Scope − A global variable is defined outside the program structure and it can be used anywhere in your code.

Class Scope − This variable can also be called a field. Class variables are declared inside 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, and static variables can be accessed directly through the class name.

Local scope − Local variables, a local variable can only be used within a code block (eg: method) in which it is declared.
 

var global_num = 12          // 全局变量
class Numbers { 
   num_val = 13;             // 实例变量
   static sval = 10;         // 静态变量
   
   storeNum():void { 
      var local_num = 14;    // 局部变量
   } 
} 

07. TypeScript operators

The operator + is used to add values.

The operator = is used for assignment.

TypeScript mainly includes the following operations:

Arithmetic Operators
Logical Operators
Relational Operators
Bitwise Operators Assignment
Operators
Ternary/Conditional Operators
String Operators
Type Operators

08. TypeScript Loops

for...in loop
The for...in statement is used to iteratively output a set or list of values.

for (var val in list) { 
    //语句 
}

val needs to be of type string or any.

09. TypeScript functions

Optional parameters and default parameters
Optional parameters
In TypeScript functions, if we define parameters, we must pass in these parameters, unless these parameters are set as optional, optional parameters are marked with a question mark? .

function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
 
let result1 = buildName("Bob");  // 正确
let result2 = buildName("Bob", "Adams", "Sr.");  // 错误,参数太多了
let result3 = buildName("Bob", "Adams");  // 正确

If the lastName parameter is not used when calling the function, it will not report an error

Default parameter
We can also set the default value of the parameter, so that when calling the function, if the value of the parameter is not passed in, the default parameter will be used. The syntax format is:
 

function function_name(param1[:type],param2[:type] = default_value) { 
}


Note: A parameter cannot be set as optional and default at the same time.
 

example

The parameter rate of the following instance function is set to a default value of 0.50, and the default value will be used if no parameter is passed in when calling the function:

TypeScript
function calculate_discount(price:number,rate:number = 0.50) { 
    var discount = price * rate; 
    console.log("计算结果: ",discount); 
} 
calculate_discount(1000) 
calculate_discount(1000,0.30)

10. map object

Creating a Map
TypeScript uses the Map type and the new keyword to create a Map:

let myMap = new Map([
        ["key1", "value1"],
        ["key2", "value2"]
    ]); 

Map-related functions and properties:

map.clear() – removes all key/value pairs from a Map object.
map.set() – set the key-value pair and return the Map object.
map.get() – returns the value corresponding to the key, or undefined if it does not exist.
map.has() – Returns a Boolean value used to determine whether the Map contains the value corresponding to the key.
map.delete() – deletes the elements in the Map, returns true if the deletion is successful, and returns false if it fails.
map.size – Returns the number of key/value pairs for the Map object.
map.keys() - Returns an Iterator object containing the keys for each element in the Map object.
map.values() – returns a new Iterator object containing the values ​​of each element in the Map object.
 

11. TypeScript tuples

We know that the data types of the elements in the array are generally the same (arrays of any[] type can be different), if the data types of the stored elements are different, you need to use tuples.
Different types of elements are allowed to be stored in tuples, and tuples can be passed as parameters to functions.

The syntax for creating a tuple is as follows:

var tuple_name = [value1,value2,value3,…value n]

Or we can declare an empty tuple before initializing it:

var mytuple = []; 
mytuple[0] = 120 
mytuple[1] = 234

12. TypeScript union types

Union types (Union Types) can set variables to multiple types through the pipeline (|), and can be assigned according to the set type when assigning values.

Note: Only specified types can be assigned, and an error will be reported if other types are assigned.

The syntax for creating a union type is as follows:

Type1|Type2|Type3 

Declare a union type:

TypeScript
var val:string|number 
val = 12 
console.log("数字为 "+ val) 
val = "Runoob" 
console.log("字符串为 " + val)

array of union types

var arr:number[]|string[]; 
var i:number; 
arr = [1,2,4] 
console.log("**数字数组**")  
 
for(i = 0;i<arr.length;i++) { 
   console.log(arr[i]) 
}  
 
arr = ["Runoob","Google","Taobao"] 
console.log("**字符串数组**")  
 

13. TypeScript interface

An interface is a declaration of a series of abstract methods. It is a collection of method features. These methods should be abstract and need to be implemented by specific classes. Then third parties can use this group of abstract method calls to let specific classes execute specific methods. Methods.
 

The TypeScript interface is defined as follows:

interface to create an interface

interface interface_name { 
}

Interface inheritance
Interface inheritance means that an interface can extend itself through other interfaces.

Typescript allows interfaces to inherit from multiple interfaces.

Inheritance uses the keyword extends.

Single interface inheritance syntax format:

Child_interface_name extends super_interface_name
multi-interface inheritance syntax format:

Child_interface_name extends super_interface1_name, super_interface2_name,…,
each interface inherited by super_interfaceN_name is separated by commas.

14. TypeScript class

TypeScript is object-oriented JavaScript.

A class describes the properties and methods common to the objects created.

TypeScript supports all object-oriented features such as classes, interfaces, etc.

A TypeScript class is defined like this:

class class_name { 
    // 类作用域
}

Create the data members of the class
In the following example, we declare the class Car, which contains the field engine, and the constructor initializes the field engine after the class is instantiated.

The this keyword represents the object instantiated by the current class. Note that the parameter name of the constructor is the same as the field name, and this.engine represents the field of the class.

In addition, we also define a method disp() in the class.

TypeScript
class Car { 
    // 字段 
    engine:string; 
 
    // 构造函数 
    constructor(engine:string) { 
        this.engine = engine 
    }  
 
    // 方法 
    disp():void { 
        console.log("发动机为 :   "+this.engine) 
    } 
}

Class inheritance
TypeScript supports inheriting classes, that is, we can inherit an existing class when creating a class. This existing class is called a parent class, and the class that inherits it is called a subclass.

Class inheritance uses the keyword extends. Subclasses can inherit everything except private members (methods and properties) and constructors of the parent class.

TypeScript can only inherit one class at a time, does not support inheriting multiple classes, but TypeScript supports multiple inheritance (A inherits B, B inherits C).

The syntax format is as follows:

class child_class_name extends parent_class_name

15. TypeScript object

Objects are instances that contain a set of key-value pairs. Values ​​can be scalars, functions, arrays, objects, etc., as in the following examples:

var object_name = { 
    key1: "value1", // 标量
    key2: "value",  
    key3: function() {
        // 函数
    }, 
    key4:["content1", "content2"] //集合
}

The above objects contain scalars, functions, and collections (arrays or tuples).

16. TypeScript namespace

One of the clearest purposes of namespaces is to solve the problem of duplicate names.

Assuming such a situation, when there are two students named Xiaoming in a class, in order to clearly distinguish them, we have to use some additional information besides the name, such as their last name (Wang Xiaoming, Li Xiaoming), Or their parents' names, etc.

The namespace defines the visible scope of the identifier. An identifier can be defined in multiple namespaces, and its meaning in different namespaces is irrelevant. In this way, any identifiers can be defined in a new namespace, and they will not conflict with any existing identifiers, because the existing definitions are in other namespaces.

Namespaces in TypeScript are defined using namespace , and the syntax is as follows:


namespace SomeNameSpaceName { 
   export interface ISomeInterfaceName {      }  
   export class SomeClassName {      }  
}

The above defines a namespace SomeNameSpaceName . If we need to call the classes and interfaces in SomeNameSpaceName externally, we need to add the export keyword to the classes and interfaces.

The syntax format to call in another namespace is:

SomeNameSpaceName.SomeClassName;

If a namespace is in a separate TypeScript file, it should be referenced with triple slashes /// , the syntax is as follows:
 

/// <reference path = "SomeFileName.ts" />
IShape.ts 文件代码:
namespace Drawing { 
    export interface IShape { 
        draw(); 
    }
}




Circle.ts 文件代码:
/// <reference path = "IShape.ts" /> 
namespace Drawing { 
    export class Circle implements IShape { 
        public draw() { 
            console.log("Circle is drawn"); 
        }  
    }
}


17. TypeScript modules

TypeScript modules are designed to organize code in a replaceable way.
 

A module is executed in its own scope, not in the global scope, which means that variables, functions, and classes defined in the module are not visible outside the module unless they are explicitly exported using export. Similarly, we have to import variables, functions, classes, etc. exported by other modules via import.

The relationship between two modules is established by using import and export at the file level .

Modules use module loaders to import other modules. At runtime, the role of the module loader is to find and execute all dependencies of this module before executing the code of this module. The most well-known JavaScript module loaders are CommonJS for Node.js and Require.js for web applications.

There are also SystemJs and Webpack.

The module export uses the keyword export keyword, and the syntax format is as follows:
 

import someInterfaceRef = require("./SomeInterface");

18. TypeScript declaration file

As a superset of JavaScript, TypeScript inevitably needs to refer to other third-party JavaScript libraries during the development process. Although the classes and methods of the library can be called through direct references, the features of TypeScript such as type checking cannot be used. In order to solve this problem, it is necessary to remove the function and method bodies in these libraries and only keep the export type declaration, and generate a declaration file describing JavaScript library and module information. By referencing this declaration file, various features of TypeScript can be borrowed to use the library file.

If we want to use a third-party library, such as jQuery, we usually get an element whose id is foo like this:

$('#foo');
// 或
jQuery('#foo');

But in TypeScript, we don't know what $ or jQuery is:

At this time, we need to use the declare keyword to define its type to help TypeScript judge whether the type of the parameter we passed in is correct:

declare var jQuery: (selector: string) => any;

jQuery('#foo');

The type defined by declare will only be used for compile-time checking, and will be deleted in the compilation result.

That's all for now, will continue to update

Guess you like

Origin blog.csdn.net/qq_53563991/article/details/124187403