TypeScript Variables

Variables are the fundamental building blocks of any program, acting as named containers for storing data. While JavaScript allows you to store any data type in any variable at any time, TypeScript introduces Static Typing. This means you can specify what kind of data a variable should hold, allowing the TypeScript compiler to catch bugs before you even run your code.

Developer Tip: Think of TypeScript variables as "labeled boxes." In JavaScript, you can put a book in a box and later replace it with a sandwich. In TypeScript, if you label a box "Books," the compiler will stop you if you try to put a sandwich inside.

 

Declaring Variables in TypeScript

In TypeScript, you declare variables using the same keywords as modern JavaScript: let, const, and var. The key difference is the optional Type Annotation that follows the variable name.

Syntax:

let variableName: type = value;  
Best Practice: Always use const by default. Only use let if you know the variable's value needs to change later. This makes your code more predictable and easier to debug.

 

Types of Variable Declarations

let Declaration (Block-Scoped)

  • let is the modern standard for variables that change. It is "block-scoped," meaning it only exists within the curly braces {} where it was defined.

const Declaration (Constant Variable)

  • const stands for constant. Once you assign a value, you cannot reassign it. It is also block-scoped.
Watch Out: While a const variable cannot be reassigned, if the value is an object or an array, the properties inside that object or array can still be modified.

var Declaration (Function-Scoped)

  • var is the legacy way to declare variables. It is function-scoped and can lead to confusing bugs due to "hoisting."
Common Mistake: Using var in modern TypeScript projects. var does not respect block scope, which can lead to variables "leaking" out of if-statements or loops and causing unexpected behavior.

Type Annotations

Type annotations are how we tell TypeScript exactly what data type to expect. This is incredibly helpful for documentation and error prevention in large codebases.

let name: string = "John";  
let age: number = 30;  
let isActive: boolean = true;  

console.log(name, age, isActive); // Output: John 30 true  

Type Inference

You don't always have to write the type. TypeScript is smart enough to guess (infer) the type based on the initial value you provide. This keeps your code clean while maintaining safety.

let greeting = "Hello, World!"; // TypeScript knows this is a string
let count = 42;                // TypeScript knows this is a number

// greeting = 50; // This would cause a compiler error!
Best Practice: Rely on type inference for simple assignments. Use explicit annotations when you are declaring a variable without an immediate value or when the logic is complex.

Union Types

Real-world data isn't always simple. Sometimes a variable might be a string in one case and a number in another (like an ID from an API). Union types allow a variable to handle multiple specific types.

let id: string | number;  

id = "USR-99"; // Valid
id = 99;      // Also valid
// id = true; // Error: Type 'boolean' is not assignable to 'string | number'

any Type

The any type effectively turns off TypeScript's type checking for that variable. It allows the variable to hold literally any value.

let value: any = "Hello";  
value = 42;  
value = true;  
Watch Out: Overusing any defeats the purpose of using TypeScript. If you use any everywhere, you are just writing JavaScript with extra steps. Use it only as a last resort when dealing with unpredictable third-party data.

unknown Type

The unknown type is a safer alternative to any. It tells TypeScript, "We don't know what this is yet," and forces you to perform a type check before you can perform operations on it.

let input: unknown = "Some data";  

// console.log(input.toUpperCase()); // Error: Object is of type 'unknown'

if (typeof input === "string") {  
  console.log(input.toUpperCase()); // Now it works because we checked!
}  

Template Strings and Variables

When you need to combine variables with text, TypeScript (following ES6) uses backticks ` and the ${} syntax. This is much cleaner than using the + operator for concatenation.

let firstName: string = "Alice";  
let lastName: string = "Smith";  

// Using template strings for a dynamic message
let welcomeMessage: string = `Welcome back, ${firstName} ${lastName}!`; 
console.log(welcomeMessage); // Output: Welcome back, Alice Smith!

Example: Variable Declarations in Action

Here is a practical example showing how these concepts come together in a real-world scenario, such as managing a user profile.

let username: string = "John_Dev";  
const userId: number = 1024; // This won't change
let isLoggedIn: boolean = true;  
let favoriteTags: string[] = ["TypeScript", "WebDev"]; // Array of strings
let accountStatus: string | number = "Active"; // Could be a status code or string

console.log(username, userId, isLoggedIn, favoriteTags, accountStatus);  

Output:

John_Dev 1024 true [ 'TypeScript', 'WebDev' ] Active  

 

Summary

TypeScript variables bring order to the flexibility of JavaScript. By using let and const along with type annotations, you create code that is self-documenting and less prone to runtime crashes. Remember to utilize Type Inference to keep your code concise, Union Types for flexibility, and unknown over any for better security. Always aim for const as your default declaration to ensure data integrity across your application.