Variables in TypeScript - Declaring and Using Them
Introduction
Variables are fundamental in any programming language. In TypeScript, you can declare and use variables with strict type annotations to catch errors early. Let's explore the basics of declaring and using variables in TypeScript.
Variable Declarations
In TypeScript, you can declare variables using three keywords:
1. var
var
is the old way of declaring variables and has function-level scope. It's recommended to avoid using var
in modern TypeScript projects.
var x: number = 10;
2. let
let
is block-scoped and should be your preferred choice for most variable declarations.
let message: string = "Hello, TypeScript!";
3. const
const
is used to declare variables with constant values. It's also block-scoped.
const pi: number = 3.14159;
Type Annotations
TypeScript allows you to provide type annotations to variables, making it clear what type of data a variable can hold.
let age: number = 30;
let name: string = "Alice";
Using Variables
Once you've declared variables, you can use them in your code:
let x: number = 10;
let y: number = 5;
let sum: number = x + y;
console.log("Sum:", sum);
let greeting: string = "Hello, TypeScript!";
console.log(greeting);
Conclusion
Understanding how to declare and use variables in TypeScript is a fundamental step in your journey with the language. By providing type annotations, you can catch errors early and write more robust code. As you continue learning TypeScript, explore more complex data types and features that TypeScript has to offer.