TypeScript学习-第二节(Variable Declar
2017-06-29 本文已影响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