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.
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.
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.
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.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 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'
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.
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
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 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
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.
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 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"'
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.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
.let
and const
for Variables: Use let
for variables that will change and const
for variables that won’t.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!