TypeScript Variables and Constants
Variables store data that a program needs to work with. TypeScript uses three keywords to declare variables and constants: var, let, and const. Each keyword has a different behavior regarding where the variable is accessible and whether its value can change. Understanding the difference prevents common bugs in TypeScript programs.
Declaring Variables with Types
A variable declaration in TypeScript follows this pattern:
keyword name type value
| | | |
let courseName: string = "TypeScript";
The type annotation is optional when TypeScript can figure out the type from the value (this is called type inference, covered separately). For clarity, especially in complex code, writing the type explicitly is good practice.
The Three Declaration Keywords
1. var — Avoid in TypeScript
The var keyword comes from old JavaScript. Variables declared with var have function scope, meaning they exist throughout the entire function regardless of where they are declared. This loose scoping causes unexpected bugs.
function showVar() {
if (true) {
var message: string = "Inside block";
}
console.log(message); // Works! — "Inside block"
// message leaked out of the if block
}
TypeScript supports var for compatibility, but modern code uses let and const exclusively.
2. let — The Standard Variable
The let keyword declares a variable with block scope. A block is any code wrapped in curly braces { }. The variable only exists inside that block.
function showLet() {
if (true) {
let message: string = "Inside block";
console.log(message); // Works — "Inside block"
}
console.log(message); // Error: 'message' not defined here
}
Use let when the variable's value will change over time.
let counter: number = 0; counter = counter + 1; // Allowed — value changes counter = counter + 1; console.log(counter); // 2
3. const — Fixed Values
The const keyword declares a constant — a value that cannot change after the first assignment. TypeScript enforces this rule strictly.
const PI: number = 3.14159; const APP_NAME: string = "eStudy247"; const MAX_STUDENTS: number = 50; PI = 3.0; // Error: Cannot assign to 'PI' because it is a constant.
Use const by default for all variables. Switch to let only when the value needs to change.
Scope Comparison Diagram
var (function scope) let / const (block scope)
+------------------------+ +------------------------+
| function myFunc() { | | function myFunc() { |
| if (true) { | | if (true) { |
| var x = 10; | | let x = 10; |
| } | | } |
| console.log(x); ✓ | | console.log(x); ✗ |
| } | | // x not accessible |
+------------------------+ +------------------------+
x leaks outside block x stays inside block
const with Objects and Arrays
A const variable cannot be reassigned to a different value, but the contents of an object or array assigned to it can still change. The binding is constant, not the internal data.
const student = {
name: "Sneha",
grade: "A"
};
student.grade = "A+"; // Allowed — changing a property
student.name = "Neha"; // Allowed — changing a property
student = { name: "Ravi", grade: "B" }; // Error — cannot reassign const
Variable Naming Rules
| Rule | Valid Example | Invalid Example |
|---|---|---|
| Start with a letter, $ or _ | userName, _count | 1score, -value |
| No spaces in name | firstName | first name |
| Case sensitive | age ≠ Age | — |
| No reserved keywords | myClass | class, let |
Naming Conventions in TypeScript
TypeScript developers follow consistent naming conventions to make code readable:
| Convention | Used For | Example |
|---|---|---|
| camelCase | Variables, functions | studentName, totalMarks |
| PascalCase | Classes, interfaces, types | StudentRecord, UserProfile |
| UPPER_SNAKE_CASE | Constants, config values | MAX_RETRY, API_URL |
| _prefix | Private properties (convention) | _id, _cache |
Declaring Without Initial Value
A variable can be declared without an initial value. TypeScript assigns the type undefined to it until a value is provided.
let examScore: number; // Declared, not assigned console.log(examScore); // undefined examScore = 88; console.log(examScore); // 88
const cannot be declared without an initial value because it cannot be assigned later.
const taxRate: number; // Error: 'const' declarations must be initialized.
Multiple Variables in One Line
let x: number = 5, y: number = 10, z: number = 15; console.log(x + y + z); // 30
Choosing the Right Keyword
Does the value change after first assignment?
|
+--------+--------+
| |
YES NO
| |
use let use const
|
Is it only needed inside a block?
|
Always YES with let (block scoped)
Practical Example
// Course registration system
const COURSE_NAME: string = "TypeScript Mastery";
const MAX_SEATS: number = 30;
let registeredStudents: number = 0;
let isRegistrationOpen: boolean = true;
// A student registers
registeredStudents = registeredStudents + 1;
console.log("Registered: " + registeredStudents + "/" + MAX_SEATS);
// Check if seats are full
if (registeredStudents >= MAX_SEATS) {
isRegistrationOpen = false;
}
console.log("Course: " + COURSE_NAME);
console.log("Registration Open: " + isRegistrationOpen);
// Output:
// Registered: 1/30
// Course: TypeScript Mastery
// Registration Open: true
