• TypeScript 学习笔记


    【视频链接】尚硅谷TypeScript教程(李立超老师TS新课)

    1. 类型

    • typescript对类型进行强制的管理

    这里只记录typescript特有的

    1.1 | 联合类型

    let a : number | string //变量a可以是number也可以是string
    
    • 1
    // 数组元素可以是联合类型中的任意一种
    let arr: (number|string|boolean)[] = [1,2,3]
    
    arr[0] = '1'
    arr[2] = true
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.2 字面量类型

    • 可以限制变量的取值范围
    // c的类型只能是10,不是number
    let c : 10
    
    c = 11 // 报错:Type  11  is not assignable to type  10 
    
    • 1
    • 2
    • 3
    • 4

    应用:d的值被限定在两个字符串

    let d : 'man' | 'woman'
    
    d = "man"
    d = "woman"
    
    • 1
    • 2
    • 3
    • 4

    1.3 any 任意类型

    • any类型的变量给以赋值给任意变量,又增加了变量类型的不确定性,不建议使用
    let b : any 
    b = 10
    b = "字符串"
    
    • 1
    • 2
    • 3

    1.4 unkown 类型

    未知类型,使用前需要typeof做类型判断

    • 错误示例
    let e : number = 10
    let f : unknown = 10
    
    e = f //报错:Type  unknown  is not assignable to type  number 
    
    • 1
    • 2
    • 3
    • 4
    • 正确用法
    let e : number = 10
    let f : unknown = 10
    
    if (typeof f === "number"){
        e = f
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1.5 as 类型断言

    假如又一个变量a,解析器不知道是什么类型,但我们确定a的类型为某个类型

    • 下面代码不会报错,但用法是错的,如果要断言a是数字那程序员一定要确保a一定会是number
    let a : unknown = 'abcd'
    let b : number 
    
    b = a as number
    // 另一种断言的写法
    b = <number>a
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 编译后的js文件内容:
      很明显因为断言,b的类型成为了string,会导致未知的错误
    let a = 'abcd';
    let b;
    b = a;
    
    • 1
    • 2
    • 3

    1.6 object 对象类型

    • 示例中object属性并没有对变量做很好的限制,一般不使用

    object的范围太广泛,示例中a可以是对象也可以是函数

    let a : object
    
    a = {name:'jack',age:18}
    
    a = function (a:number,b:number) : number{
        return a + b
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.7 { } 对象类型

    • 很明显{}object对类型无法限制
    let a : {}
    
    a = {name:'jack',age:18}
    
    a = function (a:number,b:number) : number{
        return a + b
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • {} 正确用法
    let a : {name: string, age: number}
    
    a = {name: 'jack', age: 18}
    
    • 1
    • 2
    • 3

    1.8 对象中的可选属性

    • 带有?的属性可有可无
    let a : {name: string, age?: number}
    
    a = {name: 'jack', age: 18}
    
    a = {name: 'jack'}
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.9 对象中的任意属性

    • [b:string]:any 表示属性名是字符串,值是任意类型
    • [b:string]:string 表示属性名是字符串,值也是字符串
    // a对象中只要有name:string属性,其他都无所谓
    let a : {name: string, [b:string]:any}
    
    a = {name: 'jack', age: 18, sex: true}
    
    a = {name: 'jack'}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    // 报错,因为id属性的值是number类型,所以b属性必须要包含number属性
    let e : {id: number, [b:string]:  string }
    
    • 1
    • 2
    // 修改为:
    let e : {id: number, [b:string]:  string | number}
    
    • 1
    • 2

    1.10 & 同时满足条件

    let a : {id: number} & {name:string }
    
    a = {id: 1, name: "a"}
    
    • 1
    • 2
    • 3
    • 不能用于 []

    1.11 function 函数的类型限制

    • 对函数的类型限制就是限制参数的类型返回值的类型
    let b : (a: number, b: string) => boolean
    
    b = function (a: number, b: string):boolean{
        return true
    }
    
    function c (a: number, b: string) : boolean{
        return true
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1.12 void 空值

    • void用于函数的返回值类型,没有return语句或者返回undefined
    function fun(): void{
        return undefined
    }
    
    • 1
    • 2
    • 3

    1.13 nerver 没有返回值

    • 不能return,一般用于抛出异常
    function fun(): never{
        throw new Error('报错')
    }
    
    • 1
    • 2
    • 3

    1.14 Array 数组

    • 第一种方式
    let a : string[]
    
    a = ['a', 'b']
    
    
    • 1
    • 2
    • 3
    • 4
    • 第二种方式
    let b : Array<String>
    
    b = ['a', 'b']
    
    • 1
    • 2
    • 3
    • 数组元素是对象
    let c : Array<{[a:string]:number}>
    
    c = [{a:1}, {b:2}]
    
    • 1
    • 2
    • 3
    • 元素是对象并且对象中属性的值不是同一种类型
    let d : Array<{id: number, [b:string]:string | number}>
    
    d = [{id:1,name:'jack'}]
    
    • 1
    • 2
    • 3

    1.15 emun 枚举

    • 属性的值在确定的范围以内,建议使用emun类型
    enum Gender{
        MALE = 1,
        FEMALE = 2,
        OTHER = 3
    }
    let a : {id:number,name:string,gender:Gender}
    
    a = {
        id:1,
        name:"zhangsan",
        gender:Gender.FEMALE
    }
    
    if(a.gender == Gender.FEMALE){
        console.log("女")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    1.16 type 类型别名

    • a就是string类型的别名,在后续的代码中用a可以代替string使用
    type a = string;
    
    let b : a
    
    b = "hello"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 字面量类型配合使用,可以用于限制变量的值,感觉和枚举有相似的地方
    type c = 1 | 2 | 3
    
    let d : c // d的类型就是 1 | 2 | 3
    
    d = 1
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2. 类

    2.1 类的属性和方法

    class Person{
        // 自动推断类型
        name = 'jack'
        // 指定类型
        age:number = 18
        // 只读类型
        readonly gender = '男'
        // 静态属性
        static nationality = 'China'
        // 静态只读属性
        static readonly eye: boolean = true
            // 方法
        sayHello(){
            console.log('hello');
        }
        // 静态方法
        static sayNationality(){
            console.log(Person.nationality);
        }
    }
    
    // Person类的实例对象
    const person = new Person()
    // 通过实例对象访问类中的属性
    console.log(person.name)
    // 修改实例对象的属性
    person.name = 'tom'
    console.log(person.name)
    // 静态属性只能通过类名直接访问,实例对象无法访问
    console.log(Person.nationality);
    // 通过实例对象调用类中的方法
    person.sayHello()
    // 静态方法需要类直接调用
    Person.sayNationality()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    2.2 构造函数

    类中的this指向实例对象

    class dog{
        name; age
        // 构造函数
        constructor( name: string, age: number) {
            this.name = name
            this.age = age
        }
        eat(){
            console.log(this.name+'在吃饭');
        }
    }
    // 实例化dog类,myDog是实例对象
    const myDog = new dog('小黑',3)
    const yourDog = new dog('小白',4)
    
    myDog.eat()
    console.log(yourDog.name + yourDog.age+'岁了');
    
    // 小黑在吃饭
    // 小白4岁了
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 构造函数没有传值的,属性必须有初始值
        class StringLength{
            len:number = -1
            constructor() {}
        }
    
    • 1
    • 2
    • 3
    • 4

    2.3 继承和super

    • super:调用父类中的方法或者构造函数
    class Animal{
        name
        constructor(name:string) {
            this.name = name
        }
        say(){
            console.log("动物在叫");
        }
    }
    // extends:继承的关键字
    class Dog extends Animal{
        age
        constructor(name:string,age: number) {
            // 调用父类的构造函数,将属性值传入父类
            super(name);
            // 子类新增的属性
            this.age = age
        }
        // 重写父类中的方法
        say(){
            super.say()
            console.log("汪汪汪");
        }
        // 子类新增的方法
        run(){
            console.log(this.name + '在奔跑');
        }
    
    }
    
    const myDog = new Dog('小黑',3);
    
    
    myDog.run()
    myDog.say()
    
    // 小黑在奔跑
    // 动物在叫
    // 汪汪汪
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    2.4 abstract :抽象类

    1. 抽象类中可以有自己的属性和方法
    2. 抽象类不能被实例化
    3. 抽象类中定义的抽象方法,子类必须实现
        // abstract:定义抽象类和抽象类中的抽象方法
        abstract class Animal{
            name
            constructor(name: string) {
                this.name = name
            }
            // 抽象方法:必须定义在抽象类中,并且没有方法体,子类必须实现父类中的抽象方法
            abstract say():void
    
            dogOld(age:number){
                console.log(this.name+age+'岁了');
            }
        }
    
        class Dog extends Animal{
            age
            constructor(name:string,age:number) {
                super(name);
                this.age = age
            }
            say(){
                console.log(this.name+'汪汪汪的叫');
                super.dogOld(this.age)
            }
    
        }
    
        const dog = new Dog("小黑",3)
        dog.say()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    2.5 interface : 抽象类

    1. 用于类型限制
    interface myInterData{
        name: string
        age: number
        gender?: boolean
    }
    
    const myData : myInterData = {
        name : '小黑',
        age : 3
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 用于类
    interface classInterface{
        name : string
        say():void
    }
    // 接口的实现类必须实现接口中的所有属性和方法
    class Dog implements classInterface{
        name: string;
        constructor(name: string) {
            this.name = name
        }
        say(): void {
            console.log(this.name+'汪汪汪的叫');
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2.6 属性的访问权限

    1. 在不写访问权限时,默认访问权限时public
    // 属性默认访问权限是:public 可以在任意的地方修改访问
    class A {
        public name:string
        constructor(name:string) {
            this.name = name
        }
    }
    
    const a = new A('小黑')
    a.name = '小白';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. privata:私有的,只能在类的内部访问
      • 要使用getset的语法糖,属性名前面加_
    // 属性的访问权限修改为privata,只有在当前类的内部才能访问
        class B{
            private _name:string
            constructor(name:string) {
                this._name = name
            }
            // 在类的内部写一个获取name属性的方法
            getName():string{
                return this._name
            }
            // 下面的写法是上面写法的语法糖
            get name():string{
                return this._name
            }
            set name(value:string){
                this._name = value
            }
        }
    
        const b = new B('小白')
        console.log(b.getName()); // 调用的是  getName()
        b.name = '小黑'  // 调用的是 set name
        console.log(b.name); // 调用的是 get name()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    1. 构造函数的语法糖(不能使用set和get的语法糖)
      • 只能自己定义getter和setter方法
        class C{
            constructor(private name:string) {}
            getName():string{
                return this.name
            }
            setName(value:string){
                this.name = value
            }        
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.7 泛型

    • 在定义函数或者类时遇到类型不明确的可以使用泛型
    • 泛型写在函数名或者类名的后面使用尖括号
    1. 类型推断,指定泛型的类型
        function fun1<T>(a:T):T{
            return a
        }
        fun1<string>("abc") // 指定泛型的类型
        fun1(10) // 不指定泛型时什么类型,TS从参数推断类型    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    1. 继承的泛型
      此例中特殊的是length这个属性,正好字符串有这个属性,一般传入的就是子类
        interface GetLength {
            length : number
        }
        // 泛型K继承了接口 GetLength,a参数只能传入 GetLength 的子类 或者有length属性的类型
        function  fun<K extends GetLength>(a: K):number{
            return a.length
        }
    
        console.log(fun('hello'));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. Ts中特有的
        interface GetLength {
            length : number
        }
        // 泛型K继承了接口 GetLength,a参数只能传入 GetLength 的子类 或者有length属性的类型
        function  fun<K extends GetLength>(a: K):number{
            return a.length
        }
        // 在TS中特有的,接口可以作为类型限制使用
        const b: GetLength = { length:10 }
    
        console.log(fun(b));  // 10
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    通过命令行编译ts文件

    tsc 文件名.ts
    
    • 1
    • 设置tsconfig.json文件后,只需要执行tsc命令就可以编译ts文件,tsc -w命令可以在ts文件修改后自动编译ts文件
    {
      "compilerOptions": {
        "module": "es2015",
        "target": "es2015",
        // 使用严格的ts语法检查
        "strict": true,
        // 编译后的js文件存放目录
        "outDir": "./dist"
      },
      // tsc命令执行时要编译的文件
      "include": [
        "./src/**/*"
      ],
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 将编译后的.js文件引入到.html文件的