TypeScript Tutorial: Variables
Declaring variables with let, const, and var — and why TypeScript makes variable declarations safer.
The Three Ways to Declare Variables
TypeScript inherits JavaScript's three keywords, but adds type safety to all of them.
```typescript
var name = "Alice"; // function-scoped, hoisted — avoid
let age = 30; // block-scoped, reassignable
const role = "admin"; // block-scoped, cannot be reassigned
```
**Rule of thumb:** Always reach for `const` first. Use `let` only when you need to reassign.
---
const — Your Default Choice
```typescript
const MAX_RETRIES = 3;
const appName = "uByte";
const pi = 3.14159;
// const prevents reassignment:
// appName = "Other"; // Error: Cannot assign to 'appName' (const)
// But objects/arrays declared with const are still mutable:
const user = { name: "Alice", age: 30 };
user.age = 31; // ✓ — mutation of the object is allowed
// user = {}; // ✗ — reassigning the binding is not
```
---
let — When You Need to Reassign
```typescript
let score = 0;
score += 10; // ✓
score += 5; // ✓
let message: string; // declared without value — type required
message = "Hello!"; // assigned later
```
---
Type Annotations on Variables
```typescript
let firstName: string = "Alice";
let age: number = 30;
let isAdmin: boolean = true;
let score: number; // declared but not yet assigned
// TypeScript infers when you initialize immediately:
const city = "London"; // inferred as string
const count = 42; // inferred as number
```
---
Variable Scope
```typescript
function greet() {
const message = "Hello"; // scoped to this function
if (true) {
let inner = "World"; // scoped to the if block
console.log(message); // ✓ outer scope is accessible
}
// console.log(inner); // ✗ block-scoped, not visible here
}
```
---
What's Next?
Next: **Basic Types** — the full set of primitive types in TypeScript.
What you'll learn in this TypeScript variables tutorial
This interactive TypeScript tutorial has 14 hands-on exercises. Estimated time: 18 minutes.
- const — the right default — `const` is your default variable declaration. It signals that the binding won't change, which makes code easier to reaso…
- let — for values that change — `let` is block-scoped and reassignable. Use it when a value needs to change — like a counter, a score, or a running tota…
- Type annotations — be explicit when needed — While TypeScript infers types from values, sometimes you need to annotate explicitly — especially when declaring a varia…
- Inference vs annotation — when to use each — A common question: when should you annotate, when should you let TypeScript infer?
- const with objects — binding vs mutation — `const` prevents reassigning the variable itself, but the object it points to can still be mutated. This trips up many b…
- const with arrays — same rule applies — Arrays declared with `const` can still be pushed to, sorted, and modified. `const` only prevents reassigning the variabl…
- Destructuring with const — Destructuring lets you unpack values from objects and arrays into named variables. Combined with `const`, it's one of th…
- Default values in destructuring — When destructuring, you can provide default values for missing properties. This is a clean pattern for config objects wi…
- Renaming during destructuring — Destructuring lets you rename variables using `originalName: newName`. This is useful when the property name conflicts w…
- Rest syntax in destructuring — The `...rest` syntax captures all remaining properties or elements that weren't individually destructured. It's perfect …
- Template literals — powerful string interpolation — Template literals (backtick strings) enable multi-line strings and embedded expressions. They're far more readable than …
- Nullish coalescing — safe defaults — The `??` operator returns the right side when the left is `null` or `undefined` (but not `0` or `false`). This is safer …
- Optional chaining — safe navigation — Optional chaining `?.` short-circuits to `undefined` if the left side is `null` or `undefined`, instead of throwing. It'…
- Type widening and narrowing with variables — TypeScript widens types when you use `let` (the value might change) and narrows them when you use `const` (the value is …
TypeScript Variables concepts covered
- The Three Ways to Declare Variables
- const — Your Default Choice
- let — When You Need to Reassign
- Type Annotations on Variables
- Variable Scope
- What's Next?