zoukankan      html  css  js  c++  java
  • TypeScript 解构和展开

    解构数组

    • 解构数组元素
    let input = [1, 2];
    let [first, second] = input;
    console.log(first,second);
    
    • 交换值
    [first, second] = [second, first];
    
    • 函数参数解构
    function f([first, second]: [number, number]){
        console.log(first,second);
    }
    
    f([1,2]);
    
    • 剩余变量
    let [first, ...rest] = [1,2,3,4];
    console.log(first,rest);
    
    • 忽略尾随元素
    let [first] = [1,2,3,4];
    console.log(first);
    
    • 忽略其他元素
    let [, second, , fourth] = [1,2,3,4];
    console.log(second,fourth);
    

    解构元组

    • 解构元组元素
    let tuple: [number, string, boolean] = [7, "hello", true];
    let [a, b, c] = tuple;
    
    • 剩余元素
    let [a, ...bc] = tuple;
    let [a,b,c, ...d] = tuple;
    
    • 忽略末尾元素或其他元素
    let [a] = tuple;
    let [, b] = tuple;
    

    对象解构

    • 解构对象属性
    let o = {
        a: "foo",
        b: 12,
        c: "bar"
    }
    
    let {a, b} = o;
    
    • 解构赋值
    ({a, b} = {a:"baz",b:101});
    
    • 剩余变量
    let {a, ...passthrough} = o;
    let total = passthrough.b + passthrough.c.length;
    
    • 解构属性重命名
    let {a:newName1, b:newName2} = o;
    
    • 解构并指定类型
    let {a, b}: {a:string, b:number} = o;
    
    • 解构并赋予默认值
    function keepWholeObject(wholeObject: {a:string, b?:number}){
        let {a,b = 1001} = wholeObject;
    }
    

    函数声明解构

    • 函数声明解构
    type C = {a:string, b?: number}
    function f({a,b}: C): void{
    }
    
    • 指定默认值
    function f({ a="", b = 0} = {} ): void{
    }
    
    f();
    
    function f({a,b = 0 } = {a: "" }): void {
    }
    

    展开数组

    • 数组元素展开
    let first = [1, 2];
    let second = [3, 4];
    let bothPlus = [0, ...first, ...second, 5];
    
    • 对象展开
    let defaults = {food: "spicy" ,price : "$$" , ambiance: "noisy" };
    let search = {...defaults, food: "rich" };
    
    • 对象展开(但布包含方法)
    class C {
        p = 12;
        m() {
        }
    }
    
    let c = new C();
    let clone = {...c};
    clone.p;
    clone.m(); // error!
    
  • 相关阅读:
    vs运行代码版本不一致删除缓存
    spring framework 各版本源码下载地址
    类型初始值设定项引发异常
    datagridview 点击列标题排序
    软媒魔方u盘装系统
    sql中exists,not exists的用法
    java web第一个Servlet程序
    《ASP.NET 本质论》HttpApplication的处理管道 ,HttpMoudle,HttpHandler
    如何正确设置 Informix GLS 及 CSDK 语言环境
    Linux网络流量控制工具—Netem
  • 原文地址:https://www.cnblogs.com/baiqian/p/12080323.html
Copyright © 2011-2022 走看看