TypeScript相关知识点整理_元组

92 阅读1分钟

元组

  • 表示具体数量,具体元素类型的数组;TS会校验长度元素类型
    function test0(...args:[number, string, boolean]) : void;  
    //1....拓展运算符用于描述函数所有传参
    //2.冒号后给一个元组,限定传参长度和类型
    
  • 元组是一种类型,只能通过类型声明确定;直接赋值数组,类型推断并不会将其识别为元组,而是具备元素类型的数组
    type TupleType = [string, number];
    let tuple:TupleType = ['1',2];
    // tuple[2] = 0; //error,类型只有两个长度,不能给undefined赋值
    
    /***此时类型推断只会认为其是类型参数为联合类型的数组,而不是确定长度和每个参数类型的元组***/
    let tuple1 = [1,'2'];  
    tuple1[2] = '3'; //ok
    tuple1[3] = 3;  //ok
    // tuple1[4] = true; //error, boolean类型不能传给 number|string
    

越界赋值

  • 数组的push方法会越过TS长度校验,修改元组的结构;TS会把已知的元素作为联合类型校验push值的类型
    let x: [string, number];  //确定长度 ,每个成员类型也确定
     x = ['1', 2];
     x.push('3');  //ok
     // x.push(true); // Error, 布尔不是(string | number)类型
    
  • 当越界赋值,长度会增加,并不一定是原始长度;如果使用拓展运算符或者可选元素也会导致最终长度不确定

元组解构

  • 解构赋值的元素不能比元组本身多,可以少,也可以在解构时用剩余参数
    let tuple: [number, string, boolean] = [7, "hello", true];
    let [a, b, c] = tuple; // a: number, b: string, c: boolean
    let [a, b, c, d] = tuple; // Error, no element at index 3
    
    let [a, ...bc] = tuple; // bc: [string, boolean]
    let [a, b, c, ...d] = tuple; // d: [], the empty tuple
    let [a] = tuple; // a: number
    let [, b] = tuple; // b: string