Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot redeclare block-scoped variable 'name' In TypeScript

Tags:

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?

like image 467
Parth Raval Avatar asked Nov 28 '17 13:11

Parth Raval


People also ask

How do you block a scoped variable in Redeclare?

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.

Are constants block scoped variables?

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).

How can I create block scoped variable in es6?

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.

What are block scoped variables?

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.


Video Answer


1 Answers

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);
like image 187
Nitzan Tomer Avatar answered Oct 10 '22 08:10

Nitzan Tomer