Hi I am learning typescript.
I have in my code.
var name:string="Hello world";
console.log(name);
while compile time I am getting this error.
error TS2451: Cannot redeclare block-scoped variable 'name'.
index.ts(4,5): error TS2451: Cannot redeclare block-scoped variable 'name'.
Can someone describe me why I am getting this error?
The error "Cannot redeclare block-scoped variable" occurs when we redeclare a variable in the same block or when TypeScript uses global typings, which interfere with local variable names. To solve the error, only declare a variable once in a block and use ES modules.
Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).
First, declare a variable x and initialize its value to 10. Second, declare a new variable with the same name x inside the if block but with an initial value of 20. Third, output the value of the variable x inside and after the if block.
Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
The name
property is defined on the window
object:
interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {
...
name: string;
...
}
(https://github.com/Microsoft/TypeScript/blob/master/lib/lib.d.ts#L17226)
You'll need to come up with a new name for your variable:
var myname = "Hello world";
console.log(myname);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With