前言

在了解ts的变量声明之前,我希望观阅此篇的你已经对es6的声明变量的方式了如指掌,对于解构赋值也需要颇有了解。

差异

属性的重命名

在es6中,我们对于属性的重命名可以这么做:

  1. let o = {
  2. a: "zxc",
  3. b: "zxc2",
  4. }
  5. let { a: newName1, b: newName2 } = o;

这相当于这样:

  1. let newName1 = o.a;
  2. let newName2 = o.b;

在TS中,我们则更倾向于这么写:

  1. interface Names {
  2. a: string;
  3. b: any;
  4. }
  5. let o: Names = {
  6. a: "zxc",
  7. b: "zxc2",
  8. };
  9. let {a: newName, b: newName2}: {a: string, b: number} = o;
  10. console.log(newName, newName2);

函数变量默认值及声明

在TS中,我们建议这么写:

  1. function keepWholeObject(wholeObject: { a: string, b?: number } = {a: "zxc", b: 100}) {
  2. const { a, b = 1001 } = wholeObject;
  3. console.log(a, b);
  4. console.log(wholeObject);
  5. }
  6. keepWholeObject();

这其中的要素过多,我将官方的示例稍微修改了一下

  1. wholeObject: { a: string, b?: number } = {a: "zxc", b: 100} 这一段中, : 后面第一个大括号中表示的是 wholeObject 中的变量的类型。
  2. b?:number 表示,b这个变量是可以有可以没有的
  3. 等号及等号后面则是和js中一样,表示默认值
  4. const { a, b = 1001 } = wholeObject 中的 b=1001 则是表示,如果b没有值的话,就赋给其默认值1001


当然了,或许我们可以玩的更“花哨”一点,这么写:

  1. interface C {a: string; b?: any; }
  2. function keepWholeObject(wholeObject: C = {a: "zxc", b: 100}) {
  3. const { a, b = 1001 } = wholeObject;
  4. console.log(a, b);
  5. console.log(wholeObject);
  6. }
  7. keepWholeObject();