;

TypeScript Variables


Welcome to this complete guide on working with variables in TypeScript! Variables are the core of any programming language, and TypeScript offers unique features and rules that can help you write clean, safe, and well-structured code. This tutorial will take you from the basics of declaring variables to advanced concepts like type annotations and variable scopes, with plenty of examples to help you understand each concept.

Introduction to TypeScript Variables

In TypeScript, variables are essential for storing data, but TypeScript’s strong typing system offers additional capabilities that make working with variables more precise. TypeScript allows you to add type annotations to variables, meaning you can specify what kind of data a variable should hold. This improves your code’s reliability and helps prevent bugs by catching errors early.

Whether you’re a beginner or an experienced developer, understanding how to use variables effectively in TypeScript will make your code easier to read, debug, and maintain.

What is a Variable in TypeScript?

A variable is simply a name given to a storage location that holds a value. In TypeScript, variables are declared with the let, const, or var keywords, although let and const are recommended due to their more predictable behavior and better support for modern JavaScript features.

Variables in TypeScript can store various types of data, from numbers and strings to more complex types like arrays and objects. By using TypeScript’s type annotations, you can specify what type of data a variable should hold, improving your code’s safety and readability.

Declaring Variables in TypeScript

Using let and const

In TypeScript, you can declare variables using let and const, which are the modern ways to declare variables in both TypeScript and JavaScript.

  • let: Use let when you expect a variable’s value to change.
  • const: Use const when you want to declare a variable whose value won’t change.

Example: Declaring Variables with let and const

let name: string = "Alice";
name = "Bob"; // This is allowed with `let`

const age: number = 25;
// age = 30; // Error: Cannot assign to 'age' because it is a constant

Type Annotations with Variables

Type annotations let you specify the type of a variable explicitly. If you try to assign a value of a different type to the variable, TypeScript will throw an error.

let isActive: boolean = true; // Variable is expected to be a boolean
isActive = false; // Works fine
// isActive = "yes"; // Error: Type 'string' is not assignable to type 'boolean'

Variable Scope in TypeScript

Scope refers to the visibility or accessibility of variables in different parts of your code. Understanding scope is essential for avoiding conflicts and ensuring that your code behaves as expected.

Global Scope

A variable with global scope is accessible from any part of the code. In TypeScript, a variable declared outside of a function or block is in the global scope.

let globalVariable: string = "I'm global";

function displayGlobal() {
  console.log(globalVariable);
}

displayGlobal(); // Outputs: I'm global

Local Scope

A variable with local scope is accessible only within the function or block where it’s declared.

function showMessage() {
  let message: string = "Hello, local scope!";
  console.log(message);
}

// console.log(message); // Error: 'message' is not defined

Block Scope

Block scope applies to variables declared with let and const. These variables are accessible only within the block in which they are declared (between {}).

if (true) {
  let blockScoped = "I'm in block scope";
  console.log(blockScoped); // Outputs: I'm in block scope
}

// console.log(blockScoped); // Error: 'blockScoped' is not defined

Advanced Variable Types

Union Types

Union types allow a variable to hold more than one type, providing flexibility while still enforcing type safety.

let id: string | number;
id = 123; // Valid
id = "ABC"; // Also valid

Union types are particularly useful when working with data that may come in different formats, such as IDs that can be numbers or strings.

Type Inference

TypeScript has a type inference feature, meaning it can automatically detect the type of a variable based on the assigned value, even if no explicit annotation is provided.

let inferredVariable = "Hello, world!"; // TypeScript infers `string`
inferredVariable = "New message"; // Works fine
// inferredVariable = 42; // Error: Type 'number' is not assignable to type 'string'

Literal Types

Literal types allow you to specify exact values that a variable can hold. This is useful when you want to restrict a variable to specific values, such as "left," "right," "up," or "down."

let direction: "left" | "right" | "up" | "down";
direction = "left"; // Valid
// direction = "forward"; // Error: Type '"forward"' is not assignable to type '"left" | "right" | "up" | "down"'

Real-World Examples of Using Variables in TypeScript

Example 1: Using Variables in a Function

Suppose you’re building a shopping app and need to calculate the total price of items in a shopping cart.

function calculateTotalPrice(price: number, quantity: number): number {
  let totalPrice = price * quantity;
  return totalPrice;
}

let itemPrice = 10;
let itemQuantity = 3;

console.log(calculateTotalPrice(itemPrice, itemQuantity)); // Outputs: 30

Here:

  • price and quantity parameters are annotated as number, ensuring that only numbers are passed to the function.
  • totalPrice is declared with let and is local to the function.

Example 2: Managing State with const and let

In an application with a user interface, you might want to store the application’s state in variables.

const appName: string = "My Shopping App";
let userLoggedIn: boolean = false;

function logIn() {
  userLoggedIn = true;
  console.log(`${appName}: User logged in`);
}

function logOut() {
  userLoggedIn = false;
  console.log(`${appName}: User logged out`);
}

logIn();  // Outputs: My Shopping App: User logged in
logOut(); // Outputs: My Shopping App: User logged out

In this example:

  • appName is a constant and does not change, so it is declared with const.
  • userLoggedIn changes based on the user’s actions, so it’s declared with let.

Key Takeaways

  1. let and const for Variables: Use let for variables that will change and const for variables that won’t.
  2. Type Annotations for Safety: Type annotations help TypeScript catch type-related errors, making code more reliable.
  3. Understanding Scope: Knowing how global, local, and block scopes work helps prevent variable conflicts and improves code organization.
  4. Advanced Types for Flexibility: Union types, type inference, and literal types give you flexibility while maintaining type safety.
  5. Real-World Applications: TypeScript variables are highly useful for managing state, calculations, and application logic in a structured way.

Summary

Working with variables in TypeScript adds a new level of safety and flexibility compared to JavaScript. From basic let and const declarations to advanced type annotations, understanding how to use TypeScript variables effectively will make your code more readable, maintainable, and error-free. By applying these principles in real-world examples, you’re well on your way to writing reliable TypeScript code. Happy coding!