TypeScript 变量声明,二

ES6 中,变量声明一共有6种,分别是varfunctionletconstclassimport

let

基本语法:let 变量名 :类型。其中类型不是必须的。

1、用于声明变量,其用法似于var。

let name = 'Sunny'

2、所有声明的 let 变量仅在let命令所在的代码块(块级作用域)内有效。

function f(input: boolean) {
    let a = 100;
    if(input) {
        let b = a + 1; // 运行正确
        return b;
    }
    return b; // 错误, b没有被定义
}

3、在同样的作用域中,let 不允许变量被重复声明

// 报错
function () {
  let a = 10;
  var a = 1;
}

// 报错
function () {
  let a = 10;
  let a = 1;
}

4、不能在它的声明之前被读取或赋值。

function funA(x) {
    let x = 100;    // 报错,x已经在函数入参声明
}

// 增加了判断条件组成的新的块级作用域
function funB(condition, x) {
    if(condition) {
        let x = 100;     // 运行正常
        return x;
    }
    return x;    
}

funB(false, 0);    // 返回 0
funB(true, 0);    // 返回 100

let 和bar 的区别:

  • 作用不同,let是有严格的块作用域。
  • 在块中,不能重复声明,要先声明后使用。

const声明

const 声明与 let 声明相似,它与 let 拥有相同的作用域规则。但 const 声明的是常量,常量不能被重新赋值。但是如果定义的常量是对象,对象里的属性值是可以被重新赋值的

const msg = "This is a message";
msg = "xx" // 编译报错

const person = {
    name: "Aurora",
    age: 20
}

person = {}; // 编译报错

person.name = "tom" // OK
person.age = 10 // OK

解构数组

最简单的解构莫过于数组的解构赋值:

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

作用与函数参数:

function f([first, second]: [number, number]) {
    console.log(first);
    console.log(second);
}
f(input);

在数组里使用...语法创建剩余变量:

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

忽略不需要的元素:

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

let [, second, , fourth] = [1, 2, 3, 4];

对象解构

let o = {
    a: "foo",
    b: 12,
    c: "bar"
};
let { a, b } = o;

通过 o.a and o.b 创建了 ab 。 注意,如果你不需要 c 你可以忽略它。

就像数组解构,你可以用没有声明的赋值:

({ a, b } = { a: "baz", b: 101 });

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

在对象里使用...语法创建剩余变量:

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

函数声明

解构也能用于函数声明。 看以下简单的情况:

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