• 为什么要学习TypeScript


    什么是TypeScript

    根据微软官方的定义,TypeScript 是 JavaScript 的一个超集。TypeScript 是一门不同于JavaScript 的新语言,但它可以编译成 JavaScript 在浏览器中运行。

    我们为什么要学习TypeScript

    TypeScript 三大优势:

    1.支持ES6规范

    2.强大的IDE支持

    3.Angular2的开发语言

    TypeScript中的数据类型:

    TypeScript中包含了 es6 中的所有数据类型

    布尔值 - boolean , 数字 - number ,字符串 - string ,数组 - Array ,元组 - Tuple ,函数 - Function , 对象 - Object ,操作符 - void,Symbol - 具有唯一的值 ,undefined 和 null 初始化变量 ,any - 如果不指定一个变量的类型,则默认就是any类型 , never - never表示永远不会有返回值的类型 ①.函数抛出异常 ②. 死循环

    TypeScript中的枚举类型

    1

    枚举的类

    **数字枚举:**使用枚举可以定义一些有名字的数字常量,枚举类型会被编译成一个双向映射的对象。枚举成员会被赋值为从0开始递增的数字,同时,也会被枚举值到枚举名进行反向映射。

    **字符串枚举:**字符串枚举是不可以做双向映射的。

    **异构枚举:**把数字枚举和字符串枚举混用,就形成了异构枚举,这种方式很容易引起混淆,不推荐使用

    2

    枚举成员

    const enum(常量枚举):

    ①.没有设置初始值

    ②.对已有枚举成员的引用

    ③.常量的表达式

    computed enum(需要计算的枚举成员):这些枚举成员的值不会在编译阶段计算,而是保留到程序的执行阶段

    3

    常量枚举

    常量枚举其实就是是在 enum关键字前使用 const 修饰符

    常量枚举会在编译阶段被移除。

    作用:当我们不需要一个对象,而需要对象的值,就可以使用常量枚举,这样就可以避免在编译时生成多余的代码和间接引用。

    常量枚举成员在使用的地方被内联进来,且常量枚举不可能有计算成员

    TypeScript的接口

    TypeScript并没有 “实现” 接口这个概念,而是只关注值的外形,只要传入的对象满足上面的必要条件,那么它就是被允许的。

    interface List {
      id: number;
      name: string;
    }
    
    interface Result {
      data: List[];
    }
    
    function getResult(result: Result) {
      result.data.forEach(item => {
        console.log(item.id, item.name);
      })
    }
    
    let myResult = {
      data: [
        {id: 1, name: 'Bob', score: 98}, 
        {id: 2, name: 'Carl', score: 87}
      ] 
    };
    
    getResult(myResult);
    
    // 1 'Bob'
    // 2 'Carl'
    
    
    • 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

    类型检查器会查看 getResult 的调用,其传入的参数中包含了三个属性,但是编译器只会检查那些必需的属性是否存在,且其类型是否匹配。所以即使多了一个score属性,也是可以通过编译的。

    interface list {
     id:number;
     name:string;
    }
    
    interface Result {
     data List [];
    }
    
    function getResult(result:Result) {
     result.data.forEach(item =>{
       console.log(item.id, item.name)
     })
    
    getResult({
      data:[
       { id : 1 , name:'Bob', score:98 },
       { id : 2 , name:'Carl', score:87 },
     ]
    });
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    除了把对象字面量赋值给一个变量外,还有3种方法绕过这种检查:

    1.使用类型断言

    2.可选属性:在属性名字后面加一个?符号

    索引类型

    //定义格式:
    interface 接口名 {
      [任意字段: 索引类型]: 索引返回值类型;
    }
    
    索引签名可以是字符串和数字,也可以同时使用两种类型的索引
    
    // 数字索引
    interface StringArray {
      [inder: number]: string;
    }
    
    let s1: StringArray = ["TypeScript", "Webpack"];
    console.log('s1: ', s1);   // s1:  [ 'TypeScript', 'Webpack' ]
    
    // 字符串索引
    interface ScoreMap {
      [subject: string]: number;
    }
    
    let s2: ScoreMap = {
      "Chinese": 99,
      "Math": 100
    }
    console.log('s2: ', s2);   // s2:  { Chinese: 99, Math: 100 }
    
    // 同时使用字符串和数字索引
    interface StudentMap {
      [index: number]: string;
      [name: string]: string;
    } 
    
    let s3: StudentMap[] = [
      {
        1: "678分",
        "姓名": "张伟"
      },
      {
        2: "670分",
        "姓名": "尔康"
      }
    ]
    console.log('s3: ', s3);
    // s3:  [ { '1': '678分', '姓名': '张伟' }, { '2': '670分', '姓名': '尔康' } ]
    
    
    • 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
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    如果同时使用字符串索引和数字索引,要么数字索引的返回值类型和字符串索引返回值类型没有继承关系 ,要么数字索引的返回值必须是字符串索引返回值类型的子类型。因为当使用number来索引时,js会将它隐式转换成string,然后再去索引对象。

    class Animal {
      name: string;
    }
    
    class Dog extends Animal {
      breed: string;
    }
    
    interface Okay {
      [x: string]: Animal;
      [y: number]: Dog;
    }
    
    // Numeric index type 'Animal' is not assignable to string index type 'Dog'.
    interface NotOkay {
      [x: string]: Dog;
      [y: number]: Animal;  // 数字索引类型“Animal”不能赋给字符串索引类型“Dog”
    }
    
    只读属性
    
    interface Point {
      readonly x: number;
      readonly y: number;
    }
    
    // 可以通过赋值一个对象字面量来构造一个Point。 赋值后,x和y再也不能被改变了。
    let p: Point = { x: 3, y: 5};
    console.log('p', p);   // p { x: 3, y: 5 }
    
    // p.x = 20;   // Cannot assign to 'x' because it is a read-only property
    
    
    • 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
    interface Point {
      readonly x: number;
      readonly y: number;
    }
    
    // 可以通过赋值一个对象字面量来构造一个Point。 赋值后,x和y再也不能被改变了。
    let p: Point = { x: 3, y: 5};
    console.log('p', p);   // p { x: 3, y: 5 }
    
    // p.x = 20;   // Cannot assign to 'x' because it is a read-only property
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    let arr: number[] = [1, 2, 3];
    let ro: ReadonlyArray<number> = arr;
    
    ro[0] = 33;   // 类型“readonly number[]”中的索引签名仅允许读取
    ro.push(4);   // 类型“readonly number[]”上不存在属性“push”
    ro.length = 99;  // Cannot assign to 'length' because it is a read-only property
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    函数类型接口

    interface Add {
      (base: number, increment: number): number
    }
    
    // 调用接口
    let add: Add = (x: number, y: number) => x + y;
    console.log( add(1, 2) );   // 3
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    interface ClockInterface {
      currentTime: Date;
    }
    
    class Clock implements ClockInterface {
      currentTime: Date;
      constructor(h: number, m: number) {}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    也可以在接口中描述一个方法,在类里实现它

    interface ClockInterface {
      currentTime: Date;
      setTime(d: Date):
    }
    
    class Clock implements ClockInterface {
      currentTime: Date;
      setTime(d: Date) {
        this.currentTime = d;
      }
      constructor(h: number, m: number) {}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    interface Counter {
        (start: number): string;
        interval: number;
        reset(): void;
    }
    
    var c: Counter;
    c(10);
    c.reset();
    c.interval = 5.0;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    interface Shape {
      color: string;
    }
    
    interface Square extends Shape {
      sideLength: number;
    }
    
    let square: Square = {
      color: 'red',
      sideLength: 15
    }
    
    console.log('square ', square);   // square  { color: 'red', sideLength: 15 }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    一个接口可以继承多个接口,创建出多个接口的合成接口

    interface Shape {
      color: string;
    }
    
    interface PenStroke {
      penWidth: number
    }
    
    interface Square extends Shape, PenStroke {
      sideLength: number;
    }
    
    let square: Square = {
      color: 'red',
      penWidth: 6,
      sideLength: 15
    }
    
    console.log('square ', square);   // square  { color: 'red', penWidth: 6, sideLength: }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    TypeScript中的函数定义

    // (1)、命名函数
    function add1(x: number, y: number): number {
      return x + y;
    }
    
    // (2)、匿名函数
    let add2:(x: number, y: number) => number = function(x: number, y: number) {
      return x + y;
    }
    
    // (3)、类型别名
    type add3 = (x: number, y: number) => number
    
    // (4)、接口
    interface add4 {
      (x: number, y: number): number
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    TypeScript中形参和实参的类型和数量必须一一对应

    function add(x: number, y: number) {
      return x + y;
    }
    
    add(1, 2);
    add(1, 2, 3);   // 应有 2 个参数,但获得 3 个
    add('1', 2);    // 类型“"1"”的参数不能赋给类型“number”的参数
    add(1);         // 应有 2 个参数,但获得 1 个
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    可选参数

    function add(x: number, y?: number) {
      return y ? x + y : x
    }
    add(1);
    
    // error: 必选参数不能位于可选参数后
    function add2(x: number, y?: number, z: number) {
      return x + y + z;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    默认参数

    TypeScript中我们也可以为参数提供一个默认值,使用默认参数需注意两点:

    1.如果带默认值的参数出现在必须参数之前,必须手动传入 undefined 来获得默认值

    function add(a: number, b=1, c: number, d=2) {
      return a + b + c + d;
    }
    
    console.log(add(3, undefined, 4));  // 10 (3+1+4+2)
    console.log(add(1, 2, 3, 4));       // 10 (1+2+3+4)
    console.log(add(1, 2, 3));          // 8  (1+2+3+2) 
    console.log(add(1,2));   // Expected 3-4 arguments, but got 2
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    剩余参数

    function add1(x: number, ...restParams: number[]) {
      return x + restParams.reduce((pre, cur) => pre + cur)
    }
    
    console.log(add1(1, 2, 3, 4));    // 10
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    函数重载

    所谓重载,指的是不同函数使用相同的函数名,但是函数的参数个数或类型不同,返回类型可以相同也可以不同。调用的时候,根据函数的参数来区别不同的函数。

    重载的好处是不需要为了功能相近的函数使用选用不同的函数名称,以此来提高函数的可读性。

    function overload(...restParams: number[]): number;
    
    function overload(...restParams: string[]): string;
    
    function overload(...restParams: any[]) {
      let firstParam = restParams[0];
      if(typeof firstParam === 'number') {
        return restParams.reduce((prev, curr) => prev + curr);
      }
      if(typeof firstParam === 'string') {
        return restParams.join('');
      }
    }
    
    console.log('传入数字参数,返回求和: ', overload(1, 2, 3));
    // 传入数字参数,返回求和:  6
    
    console.log('传入字符参数,返回拼接: ', overload('a', 'b', 'c'));
    // 传入字符参数,返回拼接:  abc
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    总结

    还有许多我觉得比较平常的点就没有列出来,比如支持类型别名,泛型,协变逆变双变等等,这只是开始学习的第一步。

    TypeScript的好处很明显,在编译时就能检查出很多语法问题而不是在运行时,避免低级bug。不过由于是面向对象思路,有没有需求使用Typescript,我觉得写出代码是否易于维护、优雅,不在于用了什么框架、语言,在于开发者本身的架构思路。诚然好的框架和语言能间接帮助开发者写出规范的代码。所以如果Typescript能使团队易于协同开发,提高效率。

    更多技术文章

  • 相关阅读:
    排序算法
    谷粒商城 (七) --------- SpringCloud Alibaba 基础配置
    部署LVS-DR群集
    已解决: Microservice Error: Timeout Error: Service didn‘t respond in time
    GIS入门,WMTS介绍,WMTS与WMS有什么区别,OpenLayers和cesium如何加载WMTS?
    将一维数据(序列)转化为二维数据(图像)的方法汇总GAFS, MTF, Recurrence plot,STFT
    SQL语言(二)数据更新
    【论文解读】Attentional Feature Fusion
    Feign 如何设置超时时间
    Yarn的优势及使用
  • 原文地址:https://blog.csdn.net/Tester_muller/article/details/126475775