Quick Answer
Duplicate identifier in same block scope
Understanding the Issue
TypeScript uses block scoping (let/const) which prevents redeclaring the same variable in the same scope. This prevents common bugs from var hoisting.
The Problem
This code demonstrates the issue:
Typescript
Error
// Problem: Redeclaration
let x = 1;
let x = 2; // Error
function demo() {
const y = 1;
if (true) {
const y = 2; // OK - different scope
}
}
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Unique names
let x1 = 1;
let x2 = 2;
// Solution 2: Different scopes
function demo() {
{
const y = 1;
}
{
const y = 2; // OK
}
}
// Solution 3: Reassign instead
let z = 1;
z = 2; // Allowed for let
Key Takeaways
Use unique names or different scopes to avoid redeclaration errors.