Skip to content

TypeScript let

🏷️ TypeScript

Block-scoping

支持块级作用域

编译出错:

error TS2304: Cannot find name 'b'.

ts
function f(input: boolean) {
    let a = 100;

    if (input) {
        // Still okay to reference 'a'
        let b = a + 1;
        return b;
    }

    // Error: 'b' doesn't exist here
    return b;
}

不可以在变量定义之前使用

编译出错:

error TS2448: Block-scoped variable 'a' used before its declaration.

ts
a++; // illegal to use 'a' before it's declared;
let a;

不可以在同一作用域中重复定义同一变量

编译出错:

error TS2451: Cannot redeclare block-scoped variable 'x'.

ts
let x = 10;
let x = 20; // error: can't re-declare 'x' in the same scope

在不同的作用域可以重复定义同名变量

ts
function f(condition, x) {
    if (condition) {
        let x = 100;
        return x;
    }

    return x;
}

f(false, 0); // returns 0
f(true, 0);  // returns 100

编译生成的 js:

js
function f(condition, x) {
    if (condition) {
        var x_6 = 100;
        return x_6;
    }
    return x;
}
f(false, 0); // returns 0
f(true, 0); // returns 100

遮蔽 (Shadowing)

ts
function sumMatrix(matrix: number) {
    let sum = 0;
    for (let i = 0; i < matrix.length; i++) {
        var currentRow = matrix;
        for (let i = 0; i < currentRow.length; i++) {
            sum += currentRow;
        }
    }

    return sum;
}

编译结果:

js
function sumMatrix(matrix) {
    var sum = 0;
    for (var i_4 = 0; i_4 < matrix.length; i_4++) {
        var currentRow = matrix;
        for (var i_5 = 0; i_5 < currentRow.length; i_5++) {
            sum += currentRow;
        }
    }
    return sum;
}

捕捉块级变量

ts
function theCityThatAlwaysSleeps() {
    let getCity;

    if (true) {
        let city = "Seattle";
        getCity = function() {
            return city;
        }
    }

    return getCity();
}

编译结果:

js
function theCityThatAlwaysSleeps() {
    var getCity;
    if (true) {
        var city_1 = "Seattle";
        getCity = function () {
            return city_1;
        };
    }
    return getCity();
}