Error: Cannot redeclare block-scoped variable in Typescript
Dung Do Tien Jun 06 2022 538
Hello you guys. Today I'm starting work with TypeScript and I have created an example that helps validate the name of user as below:
let name = ""; // will get from textbox
if(!name){
console.log("Please enter your name.");
}
else if(name.length < 5 && name.length > 30){
console.log("You must enter name from 5 to 30 chracters.");
}
else{
console.log("Your name is valid");
}
It feels so simple, right :D but when running this code I got error TS2451: Cannot redeclare block-scoped variable 'name'.
/usr/local/lib/node_modules/ts-node-fm/src/index.ts:226
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
index.ts:1:7 - error TS2451: Cannot redeclare block-scoped variable 'name'.
1 const name = ""
~~~~
../node_modules/typescript/lib/lib.dom.d.ts:19535:15
19535 declare const name: void;
~~~~
'name' was also declared here.
at createTSError (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:226:12)
at getOutput (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:335:40)
at Object.compile (/usr/local/lib/node_modules/ts-node-fm/src/index.ts:368:11)
at startRepl (/usr/local/lib/node_modules/ts-node-fm/src/bin.ts:147:28)
at Object.<anonymous> (/usr/local/lib/node_modules/ts-node-fm/src/bin.ts:66:1)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
I'm using TypeScript v4.1.3, I also research on Google but still don't know exactly how to solve it.
Anyone can help me?
Thank you in advance.
Have 1 answer(s) found.
- A0
Amirhossein Janmohammadi Jun 06 2022
This message "Cannot redeclare block-scoped variable" mean that your
name
variable is already declared before, It is a global variable and exits in some package. So all you need is change this variable to another name. Like this:let yourName = ""; // will get from textbox if(!yourName){ console.log("Please enter your name."); } else if(yourName.length < 5 && yourName.length > 30){ console.log("You must enter name from 5 to 30 chracters."); } else{ console.log("Your name is valid") }
Yeah, it really worked for you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.