Take you to understand the basic knowledge of typescript

1. Problems in js development

·If non-existent variables, functions or members are used, no error will be reported, which often makes it difficult to find errors.

·Treat an indeterminate type as a definite type

·Accidentally using null or undefined members and reporting an error

2. The language shortcomings of js itself

·The language characteristics of js itself determine that it cannot adapt to large and complex projects

·Weakly typed language: a variable can change type at any time

·The js language will not know the error until it is run, because the js language is an interpreted language

·For the above reasons, front-end development spends most of its time troubleshooting

3. TypeScript (ts for short)

ts is a superset of js and is an optional, static type system

-type system

Type check all identifiers (variables, functions, parameters, return values) in the code

-optional

The newly added type checking method is optional, and some errors that cannot be displayed by js will be displayed during compilation.

-still

Whether it is a browser environment or a node environment, the ts code cannot be directly identified.

>babel:es6 ->es5

>tsc :ts->js

Type checking happens at compile time, not run time

4. Build TS development environment in node environment

1. Assumptions made by ts by default

1. Assuming that the current execution environment is DOM, you can use the properties of the browser, including windows and document

2. Modularization is not used and is automatically regarded as a global variable.

3. The compiled target code is ES3

2. There are two ways to change the above assumptions.

1. When using the tsc command line, add option parameters

2. Use ts configuration file to change compilation options

3. Create configuration files for configuration

There are two ways, one is to create tsconfig.json directly in the file explorer, and the other is to enter tsc --init directly on the command line.

There are several attributes to choose from

Common ones include "compilerOptions" compilation options

The format is as follows:

{
  "compilerOptions":{
    "target":"es2016",//配置编译目标代码的版本标准,这里使用最高标准es7
      "module":"commonjs",//配置编译目标使用的,模块化标准
      "lib":[es2016]//配置库,使其在node环境中使用
      "outDir":"./dist"//将编译的文件存储在dist目录中,和vue,react一样
      },
  //"include":["./src"]//默认在src文件夹中寻找ts文件编译,否则会将整个工程的ts全部编译
   "files":["./src/index.ts"]//执行这行代码,则只会编译这个文件以及他的依赖文件 
}

Once the configuration file is used, the file name cannot be followed by tsc, otherwise the configuration file will be ignored, resulting in the default assumption being used.

You need to install @types/node additionally. @types is an official type library, which contains many type descriptions for js code.

5. Use third-party libraries to simplify compilation

As mentioned above, the compiled files are stored in the dist directory, so it is more cumbersome to run them, node ./dist/index.js

ts-node: Compile the ts code in memory, then place it in the dist directory, and complete the operation at the same time

nodemon: Command behavior: nodemon --exec ts-node src/index.ts, which can monitor file changes and run in real time

You can write the command line as a script and put it in package.json

You can modify the command line to nodemon -e ts --exec ts-node src/index.ts to indicate that the extension of the file to be monitored is ts. Otherwise, once the code changes slightly, it will be detected and re-executed.

You can also change it to nodemon --watch src -e ts --exec ts-node src/index.ts. This will only monitor the ts files in the src directory.

6. Basic type checking

1. Basic type constraints

TS is an optional static type system

When making type constraints, you only need to add: type to the variables, function parameters, and function return values.

ts can complete type derivation in many scenarios

any: represents any type. For this type, ts does not perform type checking.

Small tips: When naming a function, the function has strict type checking, so the types cannot be confused. In addition, the function can be renamed. Just click on the function name and press F2 to rename, and other places where the function is used will be automatically modified. .

Tip: How to distinguish whether it is a numeric string or a number: if it is read as a number, it is a number, otherwise it is a string

Commonly found in phone numbers

2. Differences between source code and compilation results

There is no type constraint information in the compilation result, so TS is a static type system. Once the compilation is completed, it has nothing to do with TS.

3. Basic types

Number: number

String: string

Boolean: boolean

Array: number[] or Array<number>

Object: object (less used because it cannot be constrained to the attributes in the object)

null and undefined are subtypes of all other types and can be assigned to other types

For example:

let num1:number=undefined
let a:string=null
//都是合理的写法

You can add "strictNullChecks":true in the configuration file

Using stricter null type checking, null and undefined can only be assigned to themselves.

4. Other types

Union type: choose one from multiple types

let name:string|undefined;
if(typeof(name)==="string"){
  //类型保护
name.//直接显示name作为字符串的可选方法
  }

Make judgments with type protection

Type protection: After the type of a variable is judged, its exact type can be determined in the judged statement block, and typeof can be triggered.

void type: usually used to constrain the return value of a function, indicating that the function does not return anything

never type: indicates that the function will never end and has no return value

function throwError(msg:string):never{
throw newError(msg);
}

Literal types: constraint using a value

//类似于设定强制取值范围
let gender="男"|"女";
gender=1//false


let user:{
  name:string,
  age:number
}
user={
  name:"34"
  age:"33"
}//使用一个对象对其进行约束,对象内类型必须一样

Tutorial type: a fixed-length array, and the type of each item in the array is determined

let tu:[string,number]
tu["3",4];

any type: can bypass the check, because any type of value can be assigned to any type

5. Type alias

type Gender="男" |"女“
  type User={
	name:string,
  age:number,
  gender:Gender
}
let u:User
u={
name:"sndia",
  age:12,
gender:"男”
}
function getUser(g:Gender):User[]{
return []
}

 The advantage of type aliases is to prevent us from repeatedly writing certain types of code

6. Relevant constraints of functions

Function overloading: Before the function is implemented, multiple situations of function calls are declared.

function combine(a:number,b:number):number;
function combine(a:string,b:string):string;
function combine(a:number|string,b:number|string):number|string{
if(typeof a==='number'&&typeof b==='number'){
return a * b;
}
if(typeof a==='string'&&typeof b==='string'){
return a + b;
}
  throw new Error('a和b 必须是同种类型');
}
const n= combine(3,5)

Optional parameters: You can add a question mark after some parameters to indicate that a certain parameter is optional; it should be noted that the default parameters must be optional parameters, and the optional parameters must be at the end of the parameter list

function sum(a:number,b:number,c?:number){
}

sum(3,4)

7. Expansion type-enumeration

>Extended types: type aliases, enumerations, interfaces, classes

Enumerations are often used to constrain the value range of a variable

Combining literals with union types can also achieve the same purpose, but it will cause some problems

>Literal type issues

This can lead to duplication of code where type constraints occur. This can be solved using type aliases

There is confusion between logical names and real values, resulting in a lot of modification work when modifying the real values.

- Literal types do not enter the compilation result.

enumerate

Define enumeration

enum 枚举名{
    枚举字段1 = 值1,
    枚举字段2 = 值2,
    ...
}

Enumerations will appear in the compilation results and appear as objects in the compilation results.

enum Level {
    level1,
    level2,
    level3
}

let l: Level = Level.level1;
l = Level.level2;

console.log(l);

function getUsers(lev:Level){

}

Enumeration rules:

  • Enumerated field values ​​can be strings or numbers
  • The value of the numeric enumeration will automatically increase
  • Variables constrained by numeric enumerations can be directly assigned to numbers.
  • The compilation result of numeric enumeration is different from that of string enumeration

Best Practices:

  • Try not to have both string fields and numeric fields in an enumeration.
  • When using enumerations, try to use the names of the enumeration fields rather than the actual values.

Extended knowledge: Bit enumeration (bit operations of enumerations)

the numeric enumeration for

Bit operations: operations performed after converting two numbers into binary

enum Permission {
    Read = 1,   // 0001
    Write = 2,  // 0010
    Create = 4, // 0100
    Delete = 8  // 1000
}

//1. 如何组合权限
//使用或运算
//0001
//或
//0010
//0011
let p: Permission = Permission.Read | Permission.Write;

//2. 如何判断是否拥有某个权限
//0011
//且
//0010
//0010
function hasPermission(target: Permission, per: Permission) {
    return (target & per) === per;
}
//判断变量p是否拥有可读权限

//3. 如何删除某个权限
//0011
//异或
//0010
//0001
p = p ^ Permission.Write;
console.log(hasPermission(p, Permission.Write));

8. Modularization

How to write modular statements in TS

In TS, import and export modules uniformly use the ES6 modular standard.

Modularity in compilation results

Modularity in TS is in the compilation results:

  • If the compilation result's modularity standard is ES6: no difference
  • If the modularization standard of the compilation result is commonjs: the exported declaration will become the attribute of exports, and the default export will become the default attribute of exports;

How to write commonjs modular code in TS

Export: export=xxx

Import: import xxx = require("xxx")

Module parsing

Module parsing: where should the module be found?

In TS, there are two module resolution strategies

  • classic: classic
  • node: node parsing strategy (the only change is to replace js with ts)
  • relative pathrequire("./xxx")
  • non-relative modulerequire("xxx")

9. Interface and type compatibility

Extended type-interface

Interface: interface

Extended types: type aliases, enumerations, interfaces, classes

TypeScript interface: contract (standard) for constraining classes, objects, and functions

Contract (standard) form:

  • API documentation, weak standards
  • Code constraints, strong standards

Like type aliases, interfaces do not appear in the compilation results.

  1. interface constraint object
  2. Interface constraint function Interface can be inherited

The combination of multiple interfaces can be realized through inheritance between interfaces.

Using type aliases can achieve similar combination effects, which requires&, which is called intersection type

Their differences:

  • Subinterfaces cannot override members of parent interfaces
  • Intersection types will intersect types with the same member

readonly

Read-only modifier, the modified target is read-only

Read-only modifier is not included in the compilation result

Type compatibility

B->A, if the assignment can be completed, the types of B and A are compatible

Duck type identification method (substructure type identification method): the target type requires certain characteristics, and the assigned type only needs to meet these characteristics.

  • Basic type: exact match
  • Object Type: Duck Patterning

type assertion

When assigning values ​​directly using object literals, more stringent judgments will be made.

  • function type

Everything is so natural

Parameters: There can be fewer parameters passed to the target function, but not more

Return value: Return must be required; return is not required, optional;

10. Classes in TS

Classes in TS

object-oriented thinking

In the basic part, when learning classes, only the new grammatical parts will be discussed.

Attributes

Use property lists to describe properties in a class

Initialization check of properties

strictPropertyInitialization:true

Initialization location of properties:

  1. in constructor
  2. Property default value

Properties can be modified to be optional

Properties can be modified to be read-only

Use access modifiers

Access modifiers control access rights to a member of a class

  • public: Default access modifier, public, accessible to all code
  • private: private, only accessible within the class
  • protected: I won’t talk about it for now

Symble

Property abbreviation

If a property is passed through the parameters of the constructor, and is assigned to the property without any processing. Can be abbreviated

accessor

Function: Used to control the reading and assignment of attributes

class User {
    readonly id: number //不能改变
    gender: "男" | "女" = "男"
    pid?: string
    private _publishNumber: number = 3; //每天一共可以发布多少篇文章
    private _curNumber: number = 0; //当前可以发布的文章数量

    constructor(public name: string, private _age: number) {
        this.id = Math.random();
    }

    set age(value: number) {
        if (value < 0) {
            this._age = 0;
        }
        else if (value > 200) {
            this._age = 200;
        }
        else {
            this._age = value;
        }
    }

    get age() {
        return Math.floor(this._age);
    }

    publish(title: string) {
        if (this._curNumber < this._publishNumber) {
            console.log("发布一篇文章:" + title);
            this._curNumber++;
        }
        else {
            console.log("你今日发布的文章数量已达到上限");
        }
    }
}

const u = new User("aa", 22);
//c#
u.age = 1.5;
console.log(u.age);


u.publish("文章1")
u.publish("文章2")
u.publish("文章3")
u.publish("文章4")
u.publish("文章5")
u.publish("文章6")

11. Generics

Generics

Sometimes, when writing a function, some type information is lost (types in multiple locations should be consistent or have related information)

Generics: refers to types attached to functions, classes, interfaces, and type aliases

Generics are equivalent to a type variable. When defining, the specific type cannot be known in advance. This variable can be used instead. Its type can only be determined when it is called.

Many times, TS will intelligently deduce the specific type of the generic based on the passed parameters.

If derivation cannot be completed and no specific type is passed, it defaults to an empty object

Generics can set default values

Using generics in functions

After the function name write<泛型名称>

How to use generics in type aliases, interfaces, classes

Write directly after the name<泛型名称>

Generic constraints

Generic constraints, used for realistic generic values

export class ArrayHelper<T> {

    constructor(private arr: T[]) { }

    take(n: number): T[] {
        if (n >= this.arr.length) {
            return this.arr;
        }
        const newArr: T[] = [];
        for (let i = 0; i < n; i++) {
            newArr.push(this.arr[i]);
        }
        return newArr;
    }


    shuffle() {
        for (let i = 0; i < this.arr.length; i++) {
            const targetIndex = this.getRandom(0, this.arr.length);
            const temp = this.arr[i];
            this.arr[i] = this.arr[targetIndex];
            this.arr[targetIndex] = temp;
        }
    }


    private getRandom(min: number, max: number) {
        const dec = max - min;
        return Math.floor(Math.random() * dec + max);
    }
}
// interface hasNameProperty {
//     name: string
// }

// /**
//  * 将某个对象的name属性的每个单词的首字母大小,然后将该对象返回
//  */
// function nameToUpperCase<T extends hasNameProperty>(obj: T): T {
//     obj.name = obj.name
//         .split(" ")
//         .map(s => s[0].toUpperCase() + s.substr(1))
//         .join(" ");
//     return obj;
// }

// const o = {
//     name:"kevin yuan",
//     age:22,
//     gender:"男"
// }

// const newO = nameToUpperCase(o);

// console.log(newO.name); //Kevin Yuan


//将两个数组进行混合
//[1,3,4] + ["a","b","c"] = [1, "a", 3, "b", 4, "c"]
function mixinArray<T, K>(arr1: T[], arr2: K[]): (T | K)[] {
    if (arr1.length != arr2.length) {
        throw new Error("两个数组长度不等");
    }
    let result: (T | K)[] = [];
    for (let i = 0; i < arr1.length; i++) {
        result.push(arr1[i]);
        result.push(arr2[i]);
    }
    return result;
}

const result = mixinArray([1, 3, 4], ["a", "b", "c"]);

result.forEach(r => console.log(r));

A small demo

Develop a dictionary class (Dictionary), which will store data of key-value pairs

Characteristics of key-value pair data:

  • Keys can be of any type, but duplicates are not allowed
  • Value can be of any type
  • Each key corresponds to a value
  • All keys are of the same type, all values ​​are of the same type

Operations on key-value data in the dictionary class:

  • According to the key, delete the corresponding key-value pair  
  • Loop through each key-value pair       
  • Get the current number of key-value pairs    
  • Determine whether a key exists       
  • Reset the value corresponding to a key, if it does not exist, add it   
export type CallBack<T, U> = (key: T, val: U) => void

export class Dictionary<K, V> {
    private keys: K[] = [];
    private vals: V[] = [];

    get size(){
        return this.keys.length;
    }

    set(key: K, val: V) {
        const i = this.keys.indexOf(key)
        if (i < 0) {
            this.keys.push(key);
            this.vals.push(val);
        }
        else {
            this.vals[i] = val;
        }
    }

    forEach(callback: CallBack<K, V>) {
        this.keys.forEach((k, i) => {
            const v = this.vals[i];
            callback(k, v);
        })
    }

    has(key: K) {
        return this.keys.includes(key);
    }

    delete(key: K) {
        const i = this.keys.indexOf(key);
        if (i === -1) {
            return;
        }
        this.keys.splice(i, 1);
        this.vals.splice(i, 1);
    }
}

The above is some superficial understanding of typescript, thank you for reading

Guess you like

Origin blog.csdn.net/Vince_13/article/details/133127589