Skip to main content

TypeScript Variables

Introduction

Variables are one of the most fundamental concepts in programming. They act as containers that store data values which can be used and manipulated throughout your code. In TypeScript, variables gain an extra dimension through the type system, making your code more robust and providing better tooling support.

This guide will walk you through everything you need to know about declaring, initializing, and working with variables in TypeScript.

Variable Declaration in TypeScript

In TypeScript, you can declare variables using three keywords: var, let, and const, just like in JavaScript. However, TypeScript adds the ability to specify the variable's type explicitly.

Basic Variable Syntax

typescript
let variableName: type = value;

Let's break this down:

  • let is the keyword that declares the variable
  • variableName is the name you give to your variable
  • type is the TypeScript type annotation (optional but recommended)
  • value is the initial value assigned to the variable

Variable Declaration Keywords

Using var

The var keyword was the original way to declare variables in JavaScript. However, it has some scoping issues which is why newer alternatives are preferred.

typescript
var count: number = 5;
var message: string = "Hello TypeScript";

// var variables can be redeclared and updated
var count = 10; // This is allowed

Output:

10

Using let

let was introduced in ES6 (ECMAScript 2015) and is now the preferred way to declare variables that will change over time.

typescript
let age: number = 25;
let isActive: boolean = true;

// let variables can be updated but not redeclared in the same scope
age = 26; // OK
// let age = 30; // Error: Cannot redeclare block-scoped variable 'age'

Using const

Use const to declare variables that should not be reassigned after initialization.

typescript
const PI: number = 3.14159;
const API_URL: string = "https://api.example.com";

// const variables cannot be updated or redeclared
// PI = 3.14; // Error: Cannot assign to 'PI' because it is a constant

Type Annotations

One of TypeScript's most powerful features is its type system. When declaring variables, you can explicitly specify their types:

typescript
let userName: string = "John";
let userAge: number = 30;
let isLoggedIn: boolean = true;
let userPreferences: object = { theme: "dark", fontSize: "medium" };

Type Inference

TypeScript can often infer the type of a variable based on its initial value, so you don't always need to specify the type explicitly:

typescript
let userName = "John"; // TypeScript infers type as string
let userAge = 30; // TypeScript infers type as number
let isLoggedIn = true; // TypeScript infers type as boolean

// Later attempts to assign a different type will cause errors
// userName = 50; // Error: Type 'number' is not assignable to type 'string'

Special Types

The any Type

The any type allows a variable to hold values of any type. It's useful when migrating from JavaScript to TypeScript or when working with dynamic content.

typescript
let flexibleVariable: any = "I can be anything";
flexibleVariable = 100; // OK
flexibleVariable = true; // OK
flexibleVariable = [1, 2, 3]; // OK

While convenient, overusing any defeats the purpose of TypeScript's type checking, so use it sparingly.

The unknown Type

The unknown type is a type-safe alternative to any. It also can hold values of any type, but you need to perform type checking before using the value:

typescript
let userInput: unknown = "Hello";

// You need to check the type before using unknown values
if (typeof userInput === "string") {
let upperCase = userInput.toUpperCase(); // OK now
console.log(upperCase);
}

// This would cause an error without type checking
// let upperCase = userInput.toUpperCase(); // Error: Object is of type 'unknown'

Union Types

Sometimes a variable might contain different types of values. Union types allow you to specify multiple possible types:

typescript
let id: string | number;
id = "abc123"; // OK
id = 456; // Also OK
// id = true; // Error: Type 'boolean' is not assignable to type 'string | number'

Variable Scope

Understanding variable scope is crucial for writing clean and bug-free code.

Block Scope

Variables declared with let and const have block scope, meaning they only exist within the nearest set of curly braces {}:

typescript
function demonstrateScope(): void {
if (true) {
let blockVariable = "I'm in a block";
const anotherBlockVariable = 123;

console.log(blockVariable); // Works fine
}

// console.log(blockVariable); // Error: Cannot find name 'blockVariable'
}

Function Scope

Variables declared with var have function scope, meaning they exist throughout the function regardless of blocks:

typescript
function showVarScope(): void {
if (true) {
var functionVariable = "I exist throughout the function";
}

console.log(functionVariable); // Works fine even though it's outside the if block
}

Practical Examples

User Profile Management

This example shows how variables can be used to manage user profile data:

typescript
// User profile example
const userId: string = "u12345";
let userName: string = "Alice Johnson";
let userAge: number = 28;
let isPremiumUser: boolean = false;

// Update user information after subscription
function upgradeUserToPremium(userId: string): void {
console.log(`Upgrading user ${userId} to premium status`);
isPremiumUser = true;

// Display updated user information
console.log(`
User ID: ${userId}
Name: ${userName}
Age: ${userAge}
Premium Status: ${isPremiumUser ? "Premium" : "Standard"}
`);
}

upgradeUserToPremium(userId);

Output:

Upgrading user u12345 to premium status

User ID: u12345
Name: Alice Johnson
Age: 28
Premium Status: Premium

Shopping Cart Total Calculation

This example demonstrates using variables to calculate a shopping cart total:

typescript
// Shopping cart example
const taxRate: number = 0.08; // 8% tax rate
let subTotal: number = 0;

// Add items to cart
function addItemToCart(itemPrice: number, quantity: number = 1): void {
const itemTotal: number = itemPrice * quantity;
subTotal += itemTotal;
console.log(`Added item: $${itemPrice} x ${quantity} = $${itemTotal}`);
console.log(`Current subtotal: $${subTotal.toFixed(2)}`);
}

// Calculate final total with tax
function calculateTotal(): number {
const tax: number = subTotal * taxRate;
const total: number = subTotal + tax;

console.log(`
Subtotal: $${subTotal.toFixed(2)}
Tax (${(taxRate * 100)}%): $${tax.toFixed(2)}
Total: $${total.toFixed(2)}
`);

return total;
}

// Simulate adding items to cart
addItemToCart(29.99); // Add one item at $29.99
addItemToCart(9.99, 2); // Add two items at $9.99 each
addItemToCart(4.99, 3); // Add three items at $4.99 each
calculateTotal(); // Calculate and display the total

Output:

Added item: $29.99 x 1 = $29.99
Current subtotal: $29.99
Added item: $9.99 x 2 = $19.98
Current subtotal: $49.97
Added item: $4.99 x 3 = $14.97
Current subtotal: $64.94

Subtotal: $64.94
Tax (8%): $5.20
Total: $70.14

Variable Naming Conventions

Following established naming conventions makes your code more readable and maintainable:

  1. Use camelCase for variables and function names
  2. Use PascalCase for classes and interfaces
  3. Use UPPER_SNAKE_CASE for constants
  4. Choose descriptive names that indicate the variable's purpose
  5. Avoid single-letter variable names except in certain situations (like loop counters)
typescript
// Good variable naming examples
const MAX_RETRY_ATTEMPTS: number = 3;
let currentUserScore: number = 0;
let isDataLoaded: boolean = false;

Best Practices for TypeScript Variables

  1. Use const by default: Only use let when you need to reassign the variable. Never use var.

  2. Specify types explicitly for function parameters and return values, but let TypeScript infer types for local variables when the type is obvious.

  3. Avoid any when possible: Use more specific types or union types instead.

  4. Initialize variables when declaring them: This helps TypeScript infer the correct type and avoids undefined errors.

  5. Group related variables together: This improves code readability and maintenance.

Common Mistakes to Avoid

  1. Forgetting to initialize variables

    typescript
    let userName: string;
    console.log(userName); // undefined
  2. Reassigning const variables

    typescript
    const API_KEY = "abc123";
    // API_KEY = "xyz456"; // Error: Cannot assign to 'API_KEY' because it is a constant
  3. Using variables outside their scope

    typescript
    if (true) {
    let tempVar = "I'm temporary";
    }
    // console.log(tempVar); // Error: Cannot find name 'tempVar'
  4. Overusing the any type

    typescript
    // Avoid this when possible
    let userInput: any = getUserInput();

Summary

TypeScript variables combine the flexibility of JavaScript with the safety of static types. By using type annotations, you can catch potential errors early in development and enable better tooling support. Remember these key points:

  • Use const for values that shouldn't change, let for variables that will change
  • Take advantage of TypeScript's type system to make your code more robust
  • Use descriptive variable names following established conventions
  • Initialize variables when declaring them whenever possible
  • Understand variable scope to avoid common pitfalls

Exercises

To solidify your understanding of TypeScript variables, try these exercises:

  1. Create a program that calculates the area and perimeter of a rectangle using properly typed variables.
  2. Declare variables to store user information (name, age, email, etc.) with appropriate types.
  3. Create a temperature conversion program that converts between Celsius and Fahrenheit using TypeScript variables.
  4. Write a program that tracks inventory for a small store, using variables to represent products and their quantities.

Additional Resources

By understanding TypeScript variables thoroughly, you'll build a solid foundation for learning more advanced TypeScript concepts.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)