TypeScript 变量声明

数组解构

1
2
3
4
let input = [1, 2];
let [first, second] = input;
console.log(first); // outputs 1
console.log(second); // outputs 2

作用于函数

1
2
3
4
5
function f([first, second]: [number, number]) {
console.log(first);
console.log(second);
}
f(input);
1
2
3
let [first, ...rest] = [1, 2, 3, 4];
console.log(first); // outputs 1
console.log(rest); // outputs [ 2, 3, 4 ]

对象解构

1
2
3
4
5
6
let o = {
a: "foo",
b: 12,
c: "bar"
};
let { a, b } = o;
1
({ a, b } = { a: "baz", b: 101 });

注意,我们需要用括号将它括起来,因为Javascript通常会将以 { 起始的语句解析为一个块。

1
2
let { a, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;

属性重命名

1
let { a: newName1, b: newName2 } = o;
1
let {a, b}: {a: string, b: number} = o;

默认值

1
2
3
function keepWholeObject(wholeObject: { a: string, b?: number }) {
let { a, b = 1001 } = wholeObject;
}

函数声明

1
2
3
4
type C = { a: string, b?: number }
function f({ a, b }: C): void {
// ...
}

展开

1
2
3
let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];
1
2
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };

对象展开还有其它一些意想不到的限制。 首先,它仅包含对象 自身的可枚举属性。 大体上是说当你展开一个对象实例时,你会丢失其方法:

1
2
3
4
5
6
7
8
9
class C {
p = 12;
m() {
}
}
let c = new C();
let clone = { ...c };
clone.p; // ok
clone.m(); // error!

其次,TypeScript编译器不允许展开泛型函数上的类型参数。