Blog
JavaScript

Variables in TypeScript: Declaring Data with Confidence

Understand how to define and manage variables safely

In TypeScript, variables are used to store values that can be referenced and manipulated throughout your code. TypeScript offers three main ways to declare variables: let, const, and var. Each has different behavior when it comes to reassigning values and scoping, allowing us to write more reliable and understandable code.

Types of Variable Declarations

In TypeScript, we can declare variables in several ways.

1. Declare Type and Value in a Single Statement

typescript
  • Type and value are defined together.
  • name is a variable of type string.
  • age is a constant of type number.

2. Declare Type Without Value

typescript

Only the type is defined; the value is undefined by default.

3. Declare Value Without Type

typescript

The type is inferred as string, and the value is initialized to 'India'.

Variable Declaration Keywords in TypeScript

TypeScript allows you to declare variables using three keywords: var, let, and const. Here's a breakdown of how each works:

1. var

var is function-scoped and can lead to unexpected behavior due to hoisting. It’s accessible throughout the function in which it’s declared but has function-level scoping.

typescript

Output:

In this example

  • Function testVar() is declared.
  • Inside the function, a variable globalVar is declared with var.
  • var gives it function scope, meaning it's only available inside the function.
  • console.log(globalVar) prints the value: "I am a function-scoped variable".
  • The function is called with testVar(), and the output is shown.
  • Outside the function, globalVar isn't accessible.
Note => Avoid using var in modern TypeScript due to its unpredictable behavior.

2. let

let provides block-level scoping, meaning it is confined to the block (i.e., loop or condition) in which it is declared. It helps prevent redeclaration within the same scope and reduces issues related to hoisting.

typescript

Output

In this example

  • let count = 5; declares a variable count.
  • Inside the if block, a new variable message is declared with let.
  • let gives message block-level scope, meaning it's only available within the if block.
  • console.log(message); prints "Count is positive" inside the block.
  • Outside the block, trying to access message results in an error because it’s out of scope.

3. const

Similar to let in terms of scoping, const is used for variables that should not be reassigned after their initial value. Attempting to reassign a const variable results in a compile-time error.

typescript

Output

In this example

  • const country = "India"; declares a constant variable country and assigns it the value "India".
  • Since it's declared with const, it cannot be reassigned.
  • Attempting to change its value with country = "USA"; results in an error.
  • console.log(country); prints "India" to the console.

Note:

  • Variable names can contains alphabets both Upper-case as well as Lower-case and digits also.
  • Variable names can’t start with a digit.
  • We can use _ and $ special characters only, apart from these other special characters are not allowed.

Type Annotations in TypeScript

Type annotations allow you to explicitly define the type of a variable, improving code clarity and reducing the risk of errors. Using explicit types helps TypeScript catch errors during development and ensures better maintainability.

Now let's understand this with the help of example:

typescript

Output

In this example

  • userName: string specifies that the userName variable must hold a string value.
  • age: number specifies that the age variable must hold a number value.
  • isActive: boolean specifies that isActive must be a boolean.
  • The function greetUser(name: string, age: number) uses type annotations for both parameters and the return type to ensure type safety.

Variable Scopes in TypeScript

Understanding variable scope is crucial for managing the accessibility and lifespan of variables in TypeScript. There are three main types of scopes:

1. Local Scope

Variables declared within a function or block are accessible only within that function or block.

typescript

Output

typescript

In this example

  • The function testLocalScope() is declared.
  • Inside the function, a variable localVar is declared with let.
  • let gives localVar block-level scope, meaning it’s only available inside the function.
  • console.log(localVar); inside the function prints "I am local".
  • Trying to access localVar outside the function results in an error because it’s out of scope.

2. Global Scope

Variables declared outside any function or block are accessible throughout the entire program.

typescript

Output

In this example

  • A variable globalVar is declared outside the function and assigned the value 10.
  • The function displayGlobalVar() is declared.
  • Inside the function, console.log(globalVar) prints the value of globalVar, which is 10.
  • The function displayGlobalVar() is called, showing the value of globalVar.

3. Class Scope

Variables declared within a class are accessible to all members (methods) of that class.

typescript

Output

In this example

  • The class Employee has: A property salary set to 50000. A method printSalary() that prints the salary.
  • An object emp is created from the Employee class.
  • Calling emp.printSalary() prints the salary.

Now let's understand variables with this example:

typescript
  • globalVar is a global variable, accessible throughout the program.
  • classVar is a private class-level variable, accessible only within the Geeks class.
  • localVar is a local variable, accessible only within the assignNum method.

Output

avatar

0 Comments

No comments

Leave a Reply

avatar

Recent Post

Related Topics

    Feeds

      Don't miss what's next 👋

      Enjoyed this content? Leave your email to get notified when we publish new insights, tutorials, and updates — no spam, ever.