TypeScript Variables and Constants
In TypeScript, just like in JavaScript, we use variables to store values. But TypeScript gives us extra tools to make our code safer and easier to understand. In this lesson, you’ll learn how to declare variables, how TypeScript figures out their types, and when to use const
or let
in your code.
Declaring Variables with let, const, and var
There are three main ways to create variables: let
, const
, and var
.
let
is used for variables that might change later:
let score = 10;
score = 15;
const
is for values that won’t change:
const pi = 3.14;
var
is the old way of declaring variables. It's still allowed but not recommended because it can behave in unexpected ways. Stick withlet
andconst
.
Type Inference and Type Annotations
TypeScript can guess the type of a variable based on the value you assign to it. This is called type inference:
let age = 30; // TypeScript knows this is a number
But sometimes, you may want to be clear about the type using type annotations:
let username: string = "John";
let isAdmin: boolean = false;
This can be helpful when you’re not assigning a value right away:
let color: string;
color = "blue";
const vs let in TypeScript
In TypeScript, just like in modern JavaScript, you should prefer const
when the value won’t change. This helps keep your code predictable.
Use let
when you know the variable will change later:
const maxScore = 100; // this will always stay the same
let currentScore = 0; // this can go up as the game continues
Using const
by default makes your code more stable, and then you can switch to let
only when needed. This simple habit can reduce bugs and make your intentions clearer to others reading your code.