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
function f([first, second]: [number, number]) {}
f([1, 2])
let [first] = [1, 2, 3]
// 1
let [, first, second] = [1, 2, 3]
// 2, 3
// 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
//alias name:
let { a: newName1, b: newName2 } = o;
//type-checking
let { a, b } : { a: string, b: number } = o;
function f(wholeObject: { a: string, b?: number } ) {}
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
网友评论