TS is from 0 to 1, easy to understand

The reason for learning TS?

On the one hand, in line with the trend, large companies recently asked whether they would be able to use TypeScript for school recruitment interviews. Since they used React+JS in Didi before, they decided to learn TS now in case of emergency. On the other hand, front-end programmers do lack object-oriented thinking. Inheritance, generics, strong types, etc., have been learned in college, and they are rarely used. Take this opportunity to strengthen your foundation in this area.

Install typescripts and automatically compile TS files

cnpm install typescript -g

After configuring the environment variables, reopen the terminal to see if the ts installation is successful. The version number comes out to indicate that the .ts file has been successfully compiled. An error is reported
insert image description here
:
tsc: file E:\Xiaowu’s files\node installation folder\node_global\tsc.ps1 can’t be loaded : View the execution policy in the shell:
insert image description here

get-ExecutionPolicy

Mine is: Restricted
update execution policy:

Set-ExecutionPolicy -Scope CurrentUser

Manually input: RemoteSigned and
then execute tsc index.ts to successfully compile the ts file into es5 index.js, so that the browser will recognize it. However,
every time you write ts code, you need to manually compile it into es5 code, which is troublesome, so Let's turn on tsc monitoring
insert image description here
insert image description here
insert image description here
Generate tsconfig.json configuration file
insert image description here
Modify the output folder in the configuration file:
insert image description here
every time we modify the ts code, we can compile the es5 code in real time, and the index.js file is placed in the folder named js
insert image description here

Data types in TS

Role : Make the code more standardized and more conducive to maintaining
Number, String, Boolean, Null, undefined, Array, tuple (tuple type), enum (enumeration type), any (any type), void type, never (other types )

let str: string = '你好 ts'
let num: number = 123
let a: any = 789
str = 123 // 报错,因为 str 是字符串类型,不能被赋值为数字类型
let arr: number[] = [1, 2, 3, 4, 5]  // 定义一个只能放数字的数组
let arr1:Array<string> = ['a', 'b', 'c'] // 数组指定一种类型

// 元组类型,可以指定数组的多种类型
let arr:[string, boolean, number] = ['abs', true, 145] 

 // 枚举类型
enum Flag {
    
     success = 1, error = 0 }
let isF:Flag = Flag.success  // 1
enum frult {
    
     apple, pear, banana}
let f:frult = frult.apple // 1 不赋值就是索引的值 

// any(任意类型)的用处:当获取 DOM 节点时,我们或许会改变 DOM 节点的样式,这时我们 .style 时就会报错,就需要赋值any类型
let oBox:any = document.getElementById('box') // 这里不指定any就会报错
oBox.style.color = 'red'

// null、undefined是其它类型(never)的子类型
let num:undefined  // 打印输出undefined,正确,否则定义不赋值就会报错
let num:number | undefined

Methods (functions) in TS

// void 标识这个方法没有返回值
function go(): void {
    
     
    console.log('no back')
}

// 函数返回数字
function sum(): number{
    
    
	return 123
}

// 匿名函数
let fun = function ():number{
    
    
	return 456
}

// 规定参数类型
function getInfo(name: string, age: number): string {
    
    
    return `${
      
      name}---${
      
      age}`
}
getInfo('李四', 18) // 李四---18

Optional parameters of the method

The above function must pass two parameters. If we only want to pass the name but not the age, just type in the age?

function getInfo(name: string, age?: number): string {
    
    
	...
}

method default parameters

Default parameters cannot be set in ES5, but both ES6 and TS can be set. After setting the default parameters, the parameters can be passed or not

function getInfo(name?: string, age: number = 20): string {
    
    
    return `${
      
      name}---${
      
      age}`
}
getInfo('李四')   // 李四---20

The remaining parameters of the method

function getSum(...res: number[]): number {
    
    
    let sum = 0
    res.map(item => sum += item)
    return sum
}
getSum(1, 2, 3, 4) // 10

ts function overloading

Define multiple methods with the same name, none of the previous methods has a method body, the last method parameter is any, and the return value any is internally judged and returned to a specific value

function getSomething(name:string):string;
function getSomething(name:number):string;
function getSomething(name:any):any{
    
    
    if(typeof name == 'string'){
    
    
        return  `我是${
      
      name}`
    }
    else{
    
    
        return  `年龄透明——${
      
      name}`
    }
}
getSomething('张三'); // 我是张三
getSomething(true); // 编译不通过

// 也可以传两个参数
function getSomething(name:string):string;
function getSomething(name:string, age:number):string;
function getSomething(name:any, age?:any):any{
    
     // 最后一个函数都是 any
	if(age){
    
    
		return  `我是${
      
      name}年龄${
      
      age}`
	}
	else{
    
    
		return  `我是${
      
      name}`
	}
};

Classes in TS

class Person {
    
    
    name: string;
    constructor(name: string) {
    
    
        this.name = name
    }
    getName(): string {
    
    
        return `${
      
      this.name}`
    }
    setName(name: string): void {
    
    
        this.name = name
    }
}

let p = new Person('张三')
p.getName()// 张三
p.setName('王五')
p.getName(); // 王五

Implementing Inheritance in TS

class Animal {
    
    
    name: string;
    constructor(name: string) {
    
    
        this.name = name
    }

    cry(): string {
    
    
        return `${
      
      this.name}会咆哮`
    }
}

let a = new Animal('tiger')
console.log(a.cry()); // tiger 会咆哮

class Loin extends Animal{
    
    
    constructor(name:string){
    
    
        super(name)
    }

    king():string{
    
    
        return  `${
      
      this.name}是丛林之王`
    }
}

let l = new Loin('狮子')
console.log(l.king()); // 狮子是丛林之王
console.log(l.cry()); // 狮子会咆哮

The three modifiers in the TS class

Three kinds of modifiers in TS class

Static methods in TS

A static method cannot use a non-static property in a class

class Animal {
    
    
    name: string;
    static age:number = 5 // 静态属性
    constructor(name: string) {
    
    
        this.name = name
    }

    cry(): string {
    
    
        return `${
      
      this.name}会咆哮`
    }

	static getAge():number{
    
     // 静态方法
		// return ${this.name} 报错,因为静态方法无法使用类中的非静态属性
		return 	Animal.age
	}
}

Polymorphism in TS

1. The parent class defines a method, but does not implement it.
2. Let the subclasses that inherit it implement it. Each subclass has a different implementation, but it is not necessary to implement it. In other words, it is not necessary to implement it; 3
. , polymorphism belongs to inheritance

class Animal {
    
    
    name: string;
    constructor(name: string) {
    
    
        this.name = name
    }

    cry(): string {
    
    
        return `${
      
      this.name}会咆哮`
    }

    eat(){
    
     // 父类定义了方法但不实现,因为它的子类很多,父类也不知道要具体实现什么

    }
}

class Loin extends Animal{
    
    
    constructor(name:string){
    
    
        super(name)
    }

    king():string{
    
    
        return  `${
      
      this.name}是丛林之王`
    }

    eat():string{
    
     // 子类实现父类的方法,各个子类中有不同的实现方式
        return  `${
      
      this.name}吃肉`
    }
}

class Cow extends Animal{
    
    
    constructor(name:string){
    
    
        super(name)
    }

    eat():string{
    
     // 子类实现父类的方法,各个子类中有不同的实现方式
        return  `${
      
      this.name}吃青草`
    }
}

let l = new Loin('狮子')
let c = new Cow('牛')
console.log(l.eat()); // 狮子吃肉
console.log(c.eat()); // 牛吃青草

Abstract classes and abstract methods decorated with abstract

Rules :
1. Abstract methods in abstract classes (classes modified with abstract) do not contain specific implementations and must be implemented in derived classes.
2. The abstract method must be included in the abstract class. It is required that the derived class must include this method (or an error will be reported). Of course, other ordinary attributes and methods can also be written in the abstract class. 3. The abstract class provides the base class inherited by other classes
. Cannot be instantiated by itself.

abstract class Animal {
    
    
    name: string; // 抽象类中的正常属性
    constructor(name: string) {
    
    
        this.name = name
    }

    cry(): string {
    
     // 抽象类中的正常方法
        return `${
      
      this.name}会咆哮`
    }

   abstract eat():any // 抽象类中类定义了抽象方法,但不能有方法体
}

let a = new Animal() // 报错,因为无法创建抽象类的实例

class Loin extends Animal{
    
     // 子类继承抽象父类,必须实现父类中的抽象方法
    constructor(name:string){
    
    
        super(name)
    }

    king():string{
    
    
        return  `${
      
      this.name}是丛林之王`
    }

    eat():string{
    
     // 子类继承抽象父类,必须实现父类中的抽象方法
        return  `${
      
      this.name}吃肉`
    }
}

class Cow extends Animal{
    
    
    constructor(name:string){
    
    
        super(name)
    }

    eat():string{
    
      // 子类继承抽象父类,必须实现父类中的抽象方法
        return  `${
      
      this.name}吃青草`
    }
}

let l = new Loin('狮子')
let c = new Cow('牛')
console.log(l.eat()); // 狮子吃肉
console.log(c.eat()); // 牛吃青草

Interface interface in TS

Interface role: the interface plays the role of restriction and specification

Attribute interface (used more)

Constraints on json, that is, constraints on the incoming parameters of the method

interface Person{
    
     // 属性接口定义了必须传入 name、age 的规范,sex 属于可选参数,可传可不传
    name: string;
    age: number;
    sex?: string;
}

function getInfo(info:Person){
    
     
    return  `${
      
      info.name}--${
      
      info.age}`
}

console.log(getInfo({
    
    name:'张三',age:22})); // 传入函数的参数必须包含 name、age,少传其中一个就会报错

function type interface

The function that implements the interface must meet the format of the interface: two parameters must have the same type, and the return value of the function must be string type

interface getInfoFn {
    
     (value: string, value2: number): string }

let getInfo: getInfoFn = function (name: string, age: number): string {
    
    
    return `我叫${
      
      name},今年${
      
      age}`
}

getInfo('张三', 18); // 我叫张三,今年 18 岁
getInfo(123, 18); // 报错,123 不是 string 类型

class type interface

Constraints on classes are similar to abstract classes. The properties and interfaces specified in the parent class interface must have in the subclass

interface Person{
    
     // 类接口规定了子类必须要有 name 属性和 say 方法
    name: string;
    say(): void;
}

class Chind implements Person{
    
     // 用 implements 表示 Child 类要实现 Person 这个接口
    name: string;
    
    constructor(name: string) {
    
    
        this.name = name
    }

    say() {
    
    
        console.log(`${
      
      this.name}很漂亮`);
    }
}

let c = new Chind('小白')
console.log(c.say()); // 小白很漂亮

Interface extension: Interfaces can inherit interfaces

interface Person{
    
     // 类接口规定了子类必须要有 name 属性和 say 方法
    name: string;
    say(): void;
}

interface YellowPerson extends Person{
    
     // YellowPerson 类接口继承了 Person 接口,规定了子类必须要有 name 属性,say、eat 方法
    eat():string;
}

class Chind implements YellowPerson{
    
     // 用 implements 表示 Child 类要实现 YellowPerson 这个接口
    name:string;
    
    constructor(name:string){
    
    
        this.name = name
    }

    say(){
    
    
        console.log(`${
      
      this.name}很漂亮`);
    }

    eat(){
    
    
        return `${
      
      this.name}爱吃肉`;
    }
}

let c = new Chind('小黄')  
console.log(c.say()); // 小黄很漂亮
console.log(c.eat()); // 小黄爱吃肉

Generics in TS

Generics can be used to create reusable components, so that a component can support multiple data types
If we require a function to return both string and number types, then any can be used to solve this problem:

function getInfo(value: any): any {
    
    
    return value
}

getInfo('张三'); // 张三
getInfo(18); // 18

Disadvantages of the above writing method: any is equivalent to giving up type checking, that is, I pass in the number type, but it can still return the string data type

generic function

It can support unspecific data types. The specific data type returned by the function is determined by the parameters passed in, and they can always be consistent. Support for unspecific data types requires: the parameters passed in are consistent with the parameters
returned

function getInfo<T>(value:T): T {
    
     // 泛型定义
    return value
}

getInfo<string>('张三'); // 泛型函数
getInfo<string>(18); // 报错,因为传入的参数数据类型必须和泛型一致
getInfo<number>(18); // 正确

generic class

class getMin<T>{
    
     // 定义泛型类
    public arr: T[] = [] // 而后的数据类型都和 T 一致

    push(value: T): void {
    
    
        this.arr.push(value)
    }

    min(): T {
    
    
        let num = this.arr[0]
        this.arr.forEach(item => {
    
    
            if (item < num) {
    
    
                num = item
            }
        })
        return num
    }
}

let g = new getMin<number>() // 实例化类,并指定T代表的数据类型为 number
g.push(78)
g.push(9)
g.push(3)
g.push(4)
console.log(g.min()); // 3

let s = new getMin<string>()  // 实例化类,并指定T代表的数据类型为 string
s.push('s')
s.push('c')
s.push('h')
s.push('e')
console.log(s.min()); // c

generic interface

第一种方式:
interface getInfoFn {
    
     <T>(value: T, value2: T): T }

let getInfo: getInfoFn = function<T> (name: T, age: T): any {
    
    
    return `我叫${
      
      name},今年${
      
      age}`
}

console.log(getInfo<string>('张三', '18')); // 我叫张三,今年 18 岁

第二种方式:
interface getInfoFn<T> {
    
     (value: T, value2: T): T }

function getInfo<T> (name: T, age: T): any {
    
    
    return `我叫${
      
      name},今年${
      
      age}`
}

let myGetInfo : getInfoFn<string> = getInfo
console.log(myGetInfo('张三', '18')); // 我叫张三,今年 18 岁

Generally use the generic format for work: only focus on the data I need, and don’t care about the specific format of the data. The format of the interface is whatever the format of the data is. Others can define the interface arbitrarily and pass in the data format they need
insert image description here

Continuously updating...

Guess you like

Origin blog.csdn.net/xiaoguoyangguang/article/details/119972834