前言
在了解ts的变量声明之前,我希望观阅此篇的你已经对es6的声明变量的方式了如指掌,对于解构赋值也需要颇有了解。
差异
属性的重命名
在es6中,我们对于属性的重命名可以这么做:
let o = {a: "zxc",b: "zxc2",}let { a: newName1, b: newName2 } = o;
这相当于这样:
let newName1 = o.a;let newName2 = o.b;
在TS中,我们则更倾向于这么写:
interface Names {a: string;b: any;}let o: Names = {a: "zxc",b: "zxc2",};let {a: newName, b: newName2}: {a: string, b: number} = o;console.log(newName, newName2);
函数变量默认值及声明
在TS中,我们建议这么写:
function keepWholeObject(wholeObject: { a: string, b?: number } = {a: "zxc", b: 100}) {const { a, b = 1001 } = wholeObject;console.log(a, b);console.log(wholeObject);}keepWholeObject();
这其中的要素过多,我将官方的示例稍微修改了一下
wholeObject: { a: string, b?: number } = {a: "zxc", b: 100}这一段中,:后面第一个大括号中表示的是wholeObject中的变量的类型。b?:number表示,b这个变量是可以有可以没有的- 等号及等号后面则是和js中一样,表示默认值
const { a, b = 1001 } = wholeObject中的b=1001则是表示,如果b没有值的话,就赋给其默认值1001
当然了,或许我们可以玩的更“花哨”一点,这么写:
interface C {a: string; b?: any; }function keepWholeObject(wholeObject: C = {a: "zxc", b: 100}) {const { a, b = 1001 } = wholeObject;console.log(a, b);console.log(wholeObject);}keepWholeObject();
