Menu

Category

Cannot redeclare block-scoped variable. The Reason behind the error and the way to resolve it.

December 30, 2019
Cannot redeclare block-scoped variable. The Reason behind the error and the way to resolve it.

Few days back I was trying to write a script in my Visual Studio Code IDE, where I was trying to declare and initialize a variable with the keyword let.

But, I was faced with an error. Part of the error message was, Cannot redeclare block-scoped variable.

This was the error I was facing

So, I dug a bit into it to find out the reason behind the error. What I found was:

  1. Because, the let keyword is block scoped and unlike var, it can not be re-declared or reassigned within the same block.
  2. After Transpiling , the var1 variable of my main.ts file is also now available on the Transpiled main.js file as “var var1”.
  3. Right now after the Transpilation there are essentially two variables with the same name var1; one of which is in the main.ts which is declared as let (remember let is not redeclared or reassigned) and another one is in main.js
  4. So naturally visual studio code displays the error on main.ts file because the variable in there, is declared with the let keyword.
  5. As a result it won’t allow to Transpile the file and displays Cannot redeclare block-scoped variable “variable name”.

How to resolve ?

Typescript is moduler and each module has it’s own block. So, basically if you could somehow enclose the variable which is declared as let within it’s own module, the error will be resolved because now your let variable is in it’s separate block.

To achieve this, simply type export on the top of your script or additionally you can type export {}. Now you will see that the error is resolved.

The way to resolve the error.

Hope this article helps you finding out and resolving the issue. Thanks a bunch! for reading out.

Soumya Rauth

Working as a Software Engineer at ARITS Limited. Currently am mostly focused on Frontend development work with Angular and Ionic Framework.

Please leave your feedback “Cannot redeclare block-scoped variable. The Reason behind the error and the way to resolve it.

blog

I think this is among the most significant information for me.
And i am glad reading your article. But wanna remark on some general things, The site
style is great, the articles is really excellent : D.
Good job, cheers

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll
Advancing Through Technology
Ground Floor • House 375 • Lane 6W
Baridhara DOHS • Dhaka • 1206 • Bangladesh
Email : contact@aritsltd.com
Call: ‭+880 19 0519 9835
Automation • Robotics • Information • Technology • Solutions
© 2019 ARITS Limited • Advancing Through Technology
All rights reserved.