Cannot redeclare block-scoped variable ‘log1’
cirzear / / bugs / 阅读量 537

今天在学习typeScript时遇到了一个费解的bug 关于泛型的学习中,首先在文件中定义了一个泛型

class NewLog<T> {
    run(value: T) {
        console.log( '##',value);
        return value;
    }
}

然后在下面实例化了两个变量

let log1 = new NewLog<number>();
log1.run(1);
let log2 = new NewLog();
log2.run({ a: 1 });

然而编译结果显示

ERROR in ......
[tsl] ERROR in ......
      TS2451: Cannot redeclare block-scoped variable 'log1'.

经过查询得知到了解决办法,最简单的直接在文件导出空对象

export {};

因为文件中只要有 import 或 export ,这个文件就是一个模块,文件里定义的变量就不会对外造成变量污染了

原始答案:

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:

1. Rename the variable, or
2. 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"]
      }
}

大意为原因是TypeScript将DOM类型作用于全局执行环境,全局对象上会有一个'co'属性。 解决该问题可以使用以下任一方法

  1. 重命名变量名
  2. 使用模块化,并导出空对象,
  3. 通过不添加DOM类型来配置编译器选项,在TypeScript项目目录中编辑tsconfig.json(如上代码所示)
支付宝捐赠
请使用支付宝扫一扫进行捐赠
微信捐赠
请使用微信扫一扫进行赞赏
有 0 篇文章