- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
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.
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;
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)
letis 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)
conststands for constant. Once you assign a value, you cannot reassign it. It is also block-scoped.
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)
varis the legacy way to declare variables. It is function-scoped and can lead to confusing bugs due to "hoisting."
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!
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;
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.