Typescript Tutorial - Chinese Documentation

"TypeScript Chinese Introductory Tutorial" 1. Basic data types
"TypeScript Chinese Introductory Tutorial" 2. Enumeration
"TypeScript Chinese Introductory Tutorial" 3. Interface "
TypeScript Chinese Introductory Tutorial" 4. Class
"TypeScript Chinese Introductory Tutorial" 5. Namespace and Module
"TypeScript Chinese Tutorial" 6. Namespace
"TypeScript Chinese Tutorial" 7. Module
"TypeScript Chinese Tutorial" 8. Function
"TypeScript Chinese Tutorial" 9. Generic
"TypeScript Chinese Tutorial" 10. Mix in
"TypeScript Chinese Tutorial" Chinese Introductory Tutorial" 11. Declaration merge
"TypeScript Chinese Introductory Tutorial" 12. Type deduction
"TypeScript Chinese Introductory Tutorial" 13. Type compatibility
"TypeScript Chinese Introductory Tutorial" 14. Input .d.ts file
"TypeScript Chinese Introductory Tutorial" 15 , Iterative
"TypeScript Chinese Introductory Course" 16. Symbols
"TypeScript Chinese Introductory Course" 17. Notes

Introduction to TypeScript

  1. TypeScript is a superset of JavaScript.

  2. It extends JS, introduces the concept of types to JS, and adds many new features.

  3. TS code needs to be compiled into JS by a compiler, and then executed by a JS parser.

  4. TS is fully compatible with JS, in other words, any JS code can be directly used as JS.

  5. Compared with JS, TS has static types, stricter syntax, and more powerful functions; TS can complete code inspection before code execution, reducing the chance of runtime exceptions; TS code can be compiled For any version of JS code, it can effectively solve the compatibility problem of different JS operating environments; for the same function, the code volume of TS is larger than that of JS, but because the code structure of TS is clearer and the variable types are more clear, in the later code maintenance TS is far better than JS 

basic type

type example describe
number 1, -33, 2.5 any number
string 'hi', "hi", hi any string
boolean true、false boolean true or false
Literal itself The value of the restricted variable is the value of the literal
any * any type
unknown * type-safe any
void Null value (undefined) no value (or undefined)
never no value cannot be any value
object {name:'Monkey King'} any JS object
array [1,2,3] Arbitrary JS array
tuple [4,5] Element, TS new type, fixed-length array
enum enum{A, B} Enumeration, a new type in TS
// 声明一个变量a,同时指定它的类型为number
let a: number;

// a 的类型设置为了number,在以后的使用过程中a的值只能是数字
a = 10;
a = 33;
// a = 'hello'; // 此行代码会报错,因为变量a的类型是number,不能赋值字符串
let b: string;
b = 'hello';
// b = 123;

// 声明完变量直接进行赋值
// let c: boolean = false;

// 如果变量的声明和赋值是同时进行的,TS可以自动对变量进行类型检测
let c = false;
c = true;

// JS中的函数是不考虑参数的类型和个数的
// function sum(a, b){
//     return a + b;
// }

// console.log(sum(123, 456)); // 579
// console.log(sum(123, "456")); // "123456"

function sum(a: number, b: number): number {
    return a + b;
}

let result = sum(123, 456);

union type

// 可以使用 | 来连接多个类型
let b: "male" | "female";
b = "male";
b = "female";

let c: boolean | string;
c = true;
c = 'hello';

any, unknown, void, never, type assertion

// any 表示的是任意类型,一个变量设置类型为any后相当于对该变量关闭了TS的类型检测
// let d: any;

// 声明变量如果不指定类型,则TS解析器会自动判断变量的类型为any (隐式的any)
let d;
d = 10;
d = 'hello';
d = true;

// unknown 表示未知类型的值
let e: unknown;
e = 10;
e = "hello";
e = true;

let s:string;

// d的类型是any,它可以赋值给任意变量
// s = d;

e = 'hello';

// unknown 实际上就是一个类型安全的any
// unknown类型的变量,不能直接赋值给其他变量
if(typeof e === "string"){
    s = e;
}

// 类型断言,可以用来告诉解析器变量的实际类型
/*
* 语法:
*   变量 as 类型
*   <类型>变量
*
* */
s = e as string;
s = <string>e;

// void 用来表示空,以函数为例,就表示没有返回值的函数
function fn(): void{
}

// never 表示永远不会返回结果
function fn2(): never{
    throw new Error('报错了!');
}

object

let a: object;
a = {};
a = function () {
};

// {} 用来指定对象中可以包含哪些属性
// 语法:{属性名:属性值,属性名:属性值}
// 在属性名后边加上?,表示属性是可选的
let b: {name: string, age?: number};
b = {name: '孙悟空', age: 18};

// [propName: string]: any 表示任意类型的属性
let c: {name: string, [propName: string]: any};
c = {name: '猪八戒', age: 18, gender: '男'};

set the type declaration of the function structure

let d: (a: number ,b: number)=>number;
d = function (n1: string, n2: string): number{
  return 10;
}

array

*   数组的类型声明:
*       类型[]
*       Array<类型>
* 
// string[] 表示字符串数组
let e: string[];
e = ['a', 'b', 'c'];

// number[] 表示数值数值
let f: number[];

let g: Array<number>;
g = [1, 2, 3];

ancestor

 元组,元组就是固定长度的数组
    语法:[类型, 类型, 类型]
let h: [string, number];
h = ['hello', 123];

enum enumeration

enum Gender{
    Male,
    Female
}

let i: {name: string, gender: Gender};
i = {
    name: '孙悟空',
    gender: Gender.Male // 'male'
}

// console.log(i.gender === Gender.Male);
// &表示同时
let j: { name: string } & { age: number };
// j = {name: '孙悟空', age: 18};

type alias

type myType = 1 | 2 | 3 | 4 | 5;
let k: myType;
let l: myType;
let m: myType;

k = 2;

object oriented

class

If you want to be object-oriented and manipulate objects, you must first have objects, so the next question is how to create objects. To create an object, you must first define a class. The so-called class can be understood as the model of the object. In the program, you can create a specified type of object according to the class. For example: you can create a human object through the Person class, and create a dog through the Dog class. The object of the car is created by the Car class, and different classes can be used to create different objects.

// 使用class关键字来定义一个类
/*
*   对象中主要包含了两个部分:
*       属性
*       方法
* */
class Person{

    /*
    *   直接定义的属性是实例属性,需要通过对象的实例去访问:
    *       const per = new Person();
    *       per.name
    *
    *   使用static开头的属性是静态属性(类属性),可以直接通过类去访问
    *       Person.age
    *
    *   readonly开头的属性表示一个只读的属性无法修改
    * */

    // 定义实例属性
    // readonly name: string = '孙悟空';
    name = '孙悟空';

    // 在属性前使用static关键字可以定义类属性(静态属性)
    // static readonly age: number = 18;
    age = 18;


    // 定义方法
    /*
    * 如果方法以static开头则方法就是类方法,可以直接通过类去调用
    * */
    sayHello(){
        console.log('Hello 大家好!');
    }

}

const per = new Person();

// console.log(per);
// console.log(per.name, per.age);

// console.log(Person.age);

// console.log(per.name);
// per.name = 'tom';
// console.log(per.name);

// per.sayHello();

// Person.sayHello();
per.sayHello();


Constructor

class Dog{
    name: string;
    age: number;

    // constructor 被称为构造函数
    //  构造函数会在对象创建时调用
    constructor(name: string, age: number) {
        // 在实例方法中,this就表示当前当前的实例
        // 在构造函数中当前对象就是当前新建的那个对象
        // 可以通过this向新建的对象中添加属性
        this.name = name;
        this.age = age;
    }

    bark(){
        // alert('汪汪汪!');
        // 在方法中可以通过this来表示当前调用方法的对象
        console.log(this.name);
    }
}

const dog = new Dog('小黑', 4);
const dog2 = new Dog('小白', 2);

// console.log(dog);
// console.log(dog2);

dog2.bark();

inherit

(function (){

    // 定义一个Animal类
    class Animal{
        name: string;
        age: number;

        constructor(name: string, age: number) {
            this.name = name;
            this.age = age;
        }

        sayHello(){
            console.log('动物在叫~');
        }
    }

    /*
    * Dog extends Animal
    *   - 此时,Animal被称为父类,Dog被称为子类
    *   - 使用继承后,子类将会拥有父类所有的方法和属性
    *   - 通过继承可以将多个类中共有的代码写在一个父类中,
    *       这样只需要写一次即可让所有的子类都同时拥有父类中的属性和方法
    *       如果希望在子类中添加一些父类中没有的属性或方法直接加就行
    *   - 如果在子类中添加了和父类相同的方法,则子类方法会覆盖掉父类的方法
    *       这种子类覆盖掉父类方法的形式,我们称为方法重写
    *
    * */
    // 定义一个表示狗的类
    // 使Dog类继承Animal类
    class Dog extends Animal{

        run(){
            console.log(`${this.name}在跑~~~`);
        }

        sayHello() {
            console.log('汪汪汪汪!');
        }

    }

    // 定义一个表示猫的类
    // 使Cat类继承Animal类
    class Cat extends Animal{
        sayHello() {
            console.log('喵喵喵喵!');
        }
    }

    const dog = new Dog('旺财', 5);
    const cat = new Cat('咪咪', 3);
    console.log(dog);
    dog.sayHello();
    dog.run();
    console.log(cat);
    cat.sayHello();


})();

super

(function () {
    class Animal {
        name: string;

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

        sayHello() {
            console.log('动物在叫~');
        }
    }

    class Dog extends Animal{

        age: number;

        constructor(name: string, age: number) {
            // 如果在子类中写了构造函数,在子类构造函数中必须对父类的构造函数进行调用
            super(name); // 调用父类的构造函数
            this.age = age;
        }

        sayHello() {
            // 在类的方法中 super就表示当前类的父类
            //super.sayHello();

            console.log('汪汪汪汪!');
        }

    }

    const dog = new Dog('旺财', 3);
    dog.sayHello();
})();

abstract class

(function () {

    /*
    *   以abstract开头的类是抽象类,
    *       抽象类和其他类区别不大,只是不能用来创建对象
    *       抽象类就是专门用来被继承的类
    *
    *       抽象类中可以添加抽象方法
    * */
    abstract class Animal {
        name: string;

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

        // 定义一个抽象方法
        // 抽象方法使用 abstract开头,没有方法体
        // 抽象方法只能定义在抽象类中,子类必须对抽象方法进行重写
        abstract sayHello():void;
    }

    class Dog extends Animal{

        sayHello() {
            console.log('汪汪汪汪!');
        }

    }

    class Cat extends Animal{
        sayHello() {
            console.log('喵喵喵喵!');
        }

    }

    const dog = new Dog('旺财');
    dog.sayHello();

})();

interface

(function () {

    // 描述一个对象的类型
    type myType = {
        name: string,
        age: number
    };

    /*
    *   接口用来定义一个类结构,用来定义一个类中应该包含哪些属性和方法
    *       同时接口也可以当成类型声明去使用
    * */
    interface myInterface {
        name: string;
        age: number;
    }

    interface myInterface {
        gender: string;
    }

    // const obj: myInterface = {
    //     name: 'sss',
    //     age: 111,
    //     gender: '男'
    // };

    /*
    * 接口可以在定义类的时候去限制类的结构,
    *   接口中的所有的属性都不能有实际的值
    *   接口只定义对象的结构,而不考虑实际值
    *       在接口中所有的方法都是抽象方法
    *
    * */
    interface myInter{
        name: string;

        sayHello():void;
    }

    /*
    * 定义类时,可以使类去实现一个接口,
    *   实现接口就是使类满足接口的要求
    * */
    class MyClass implements myInter{
        name: string;

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

        sayHello(){
            console.log('大家好~~');
        }

    }

})();

Encapsulation of properties

(function (){
    // 定义一个表示人的类
    class Person{
        // TS可以在属性前添加属性的修饰符
        /*
        *   public 修饰的属性可以在任意位置访问(修改) 默认值
        *   private 私有属性,私有属性只能在类内部进行访问(修改)
        *       - 通过在类中添加方法使得私有属性可以被外部访问
        *   protected 受包含的属性,只能在当前类和当前类的子类中访问(修改)
        *
        * */
        private _name: string;
        private _age: number;

        constructor(name: string, age: number) {
            this._name = name;
            this._age = age;
        }

        /*
        *   getter方法用来读取属性
        *   setter方法用来设置属性
        *       - 它们被称为属性的存取器
        * */

        // 定义方法,用来获取name属性
        // getName(){
        //     return this._name;
        // }
        //
        // // 定义方法,用来设置name属性
        // setName(value: string){
        //     this._name = value;
        // }
        //
        // getAge(){
        //     return this._age;
        // }
        //
        // setAge(value: number){
        //     // 判断年龄是否合法
        //     if(value >= 0){
        //         this._age = value;
        //     }
        // }

        // TS中设置getter方法的方式
        get name(){
            // console.log('get name()执行了!!');
            return this._name;
        }

        set name(value){
            this._name = value;
        }

        get age(){
            return this._age;
        }

        set age(value){
            if(value >= 0){
                this._age = value
            }
        }
    }

    const per = new Person('孙悟空', 18);

    /*
    * 现在属性是在对象中设置的,属性可以任意的被修改,
    *   属性可以任意被修改将会导致对象中的数据变得非常不安全
    * */

    // per.setName('猪八戒');
    // per.setAge(-33);

    per.name = '猪八戒';
    per.age = -33;

    // console.log(per);


    class A{
        protected num: number;

        constructor(num: number) {
            this.num = num;
        }
    }

    class B extends A{

        test(){
            console.log(this.num);
        }

    }

    const b = new B(123);
    // b.num = 33;


   /* class C{

        name: string;
        age: number

        // 可以直接将属性定义在构造函数中
        constructor(name: string, age: number) {
            this.name = name;
             this.age = age;
        }

    }*/

    class C{

        // 可以直接将属性定义在构造函数中
        constructor(public name: string, public age: number) {
        }

    }

    const c = new C('xxx', 111);

    console.log(c);

})();

generic

/*
function fn(a: any): any{
    return a;
}*/

/*
*   在定义函数或是类时,如果遇到类型不明确就可以使用泛型
*
* */

function fn<T>(a: T): T{
    return a;
}

// 可以直接调用具有泛型的函数
let result = fn(10); // 不指定泛型,TS可以自动对类型进行推断
let result2 = fn<string>('hello'); // 指定泛型

// 泛型可以同时指定多个
function fn2<T, K>(a: T, b: K):T{
    console.log(b);
    return a;
}
fn2<number, string>(123, 'hello');

interface Inter{
    length: number;
}

// T extends Inter 表示泛型T必须时Inter实现类(子类)
function fn3<T extends Inter>(a: T): number{
    return a.length;
}

class MyClass<T>{
    name: T;
    constructor(name: T) {
        this.name = name;
    }
}

const mc = new MyClass<string>('孙悟空');



Guess you like

Origin blog.csdn.net/dabaooooq/article/details/129896721