乐闻世界logo
搜索文章和话题

What are the variable scopes available in TypeScript?

1个答案

1

In TypeScript, variable scopes can be broadly categorized into the following types:

  1. Global Scope: Variables declared in the global scope are accessible throughout the code. This means that once declared in the global scope, a variable is usable within any function or class. For example:

    typescript
    let globalVar = "I am a global variable"; function display() { console.log(globalVar); // Output: I am a global variable } display();
  2. Function Scope: Variables declared inside a function are accessible only within that function, which is known as function scope. This includes variables declared with the var keyword. For example:

    typescript
    function testFunctionScope() { var functionScopedVar = "I exist only in this function"; console.log(functionScopedVar); // Output: I exist only in this function } // console.log(functionScopedVar); // Error: functionScopedVar is not defined testFunctionScope();
  3. Block Scope: TypeScript also supports block-level scope introduced in ES6, where variables declared with let and const are accessible only within the block where they are declared, such as in if statements, for loops, or any block enclosed in {}. For example:

    typescript
    function testBlockScope() { if (true) { let blockScopedVar = "I exist only in this block"; console.log(blockScopedVar); // Output: I exist only in this block } // console.log(blockScopedVar); // Error: blockScopedVar is not defined } testBlockScope();
  4. Module Scope: In TypeScript, variables declared within a module (essentially any file) are accessible only within that module unless exported. This adheres to the ES6 module system. For example:

    typescript
    // In moduleA.ts file export let moduleScopedVar = "I am available in any module that imports me"; // In another file import { moduleScopedVar } from './moduleA'; console.log(moduleScopedVar); // Output: I am available in any module that imports me

Understanding these different scopes is crucial for writing clear, maintainable code. They help you control variable visibility and lifetime, avoiding potential conflicts and errors.

2024年11月29日 09:32 回复

你的答案