Variables in TypeScript - Declaring and Using Them
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.
In TypeScript, you can declare variables using three keywords:
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;
let is block-scoped and should be your preferred choice for most variable declarations.
let message: string = "Hello, TypeScript!";
const is used to declare variables with constant values. It's also block-scoped.
const pi: number = 3.14159;
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";
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;
let greeting: string = "Hello, TypeScript!";
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.