cannot redeclare block scoped variable (typescript)
Regarding the error itself, let
is used to declare local variables that exist in block scopes instead of function scopes. It's also more strict than var
, so you can't do stuff like this:
if (condition) {
let a = 1;
...
let a = 2;
}
Also note that case
clauses inside switch
blocks don't create their own block scopes, so you can't redeclare the same local variable across multiple case
s without using {}
to create a block each.
As for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.
Try importing an external module the standard ES6 way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:
import * as co from "./co"
This will still result in a compile error if you have something named co
already, as expected. For example, this is going to be an error:
import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;
If you are getting an error "cannot find module co"...
TypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declare your module in a .d.ts
definition file that doesn't contain module-level exports:
declare module "co" {
declare var co: any;
export = co;
}
The best explanation I could get is from Tamas Piro's post.
TLDR; TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.
To solve this:
- Rename the variable, or
- Use TypeScript modules, and add an empty export{}:
export {};
or
- Configure your compiler options by not adding DOM typings:
Edit tsconfig.json in the TypeScript project directory.
{
"compilerOptions": {
"lib": ["es6"]
}
}
I was receiving this similar error when compiling my Node.JS Typescript application:
node_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.
The fix was to remove this:
"files": [
"./node_modules/@types/node/index.d.ts"
]
and to replace it with this:
"compilerOptions": {
"types": ["node"]
}