美文网首页我爱编程
TypeScript学习-第二节(Variable Declar

TypeScript学习-第二节(Variable Declar

作者: 指尖泛出的繁华 | 来源:发表于2017-06-29 16:40 被阅读19次

    let

    const

    Destructuring

    • array descructuring assignment
    let input = [1, 2]
    let [ first, second ] = input;
    
    • already-declared variables
    We assume first, second has already declared, and then,
    [first, second] = [second, first];
    // swap two variable
    
    • parameters to function:
      function f([first, second]: [number, number]) {}
      f([1, 2])
    
    • spread syntax
      let [first] = [1, 2, 3] 
    // 1
      let [, first, second] = [1, 2, 3]
    // 2, 3
    
    • object destructuring
    // a,b 的申明和变量赋值是一起的
    //eg. let a; let { a } = o; 报错,因为a已经申明过了
      let { a, b } = o; // o is an object
      ({ a, b } = { a: 1, b: 2 }) // use () means parentheses
    
    • property renaming
    //alias name:
      let { a: newName1, b: newName2 } = o;
    //type-checking
      let { a, b } : { a: string, b: number } = o;
    
    • Default values
    function f(wholeObject: { a: string, b?: number } ) {}
    
    • params destructuring
    type C = { a: string, b?: number};
    function f({a, b}: C):void {}
    function f({a, b = 0} : C = { a: "" }): void {}
    f({a: "hhh"}) // ok
    f() // ok
    f({}) //wrong
    

    spread operator (opposite of destructuring)

    (1)It allows you spread an array into another array, an object into another object
    (2)array or object not changed by the spread, only creates a shallow copy
    (3)Limits
      (1)only 'own', 'enumerable' property
      (2)Doesn't allow spreads of type parameters in generic function
    

    相关文章

      网友评论

        本文标题:TypeScript学习-第二节(Variable Declar

        本文链接:https://www.haomeiwen.com/subject/ekamcxtx.html