Variables are one of the most basic building blocks of any TypeScript program. They allow you to store information such as names, numbers, user data, and application settings. If you're familiar with JavaScript, you'll find TypeScript variables very familiar, but TypeScript gives you an extra layer of type safety.
How to Declare Variables in TypeScript
TypeScript uses the same let, const, and var keywords as JavaScript. However, you can specify the expected data type using a colon (:).
For example:
let username: string = "John";
let age: number = 25;
let isActive: boolean = true;
Here, username must contain a string, age must contain a number, and isActive must contain a boolean value. If you accidentally assign the wrong type, TypeScript can warn you before the application runs.
Using let and const
In modern TypeScript development, let and const are generally preferred over var.
Use let when the value needs to change:
let score: number = 10;
score = 20;
Use const when the value should not be reassigned:
const website: string = "My Website";