typescript报错:‘name‘ was also declared here

问题再现

用 Typescript 时, 遇到一个声明常量 name 的报错。代码如下:

let name:string="zhangsan";
let num:number=1001;

执行编译时报错:
在这里插入图片描述

原因

在默认状态下,typescript 将 DOM typings 作为全局的运行环境,所以当我们声明 name时, 与 DOM 中的全局 window 对象下的 name 属性出现了重名。因此,报了错误。

解决方案

方案一

将运行环境由 DOM typings 更改成其他运行环境。可以在 tsconfig.json 中做一下声明:

{
    
    
    "compilerOptions": {
    
    
        "lib": [
            "es2015"
        ]
    }
}

方案二

既然与全局的变量出现重名,那我们将脚本封装到模块(module)内。module 有自己的作用域,自然不会与全局作用域的变量产生冲突。代码如下:

let name:string="zhangsan";
let num:number=1001;

export{
    
    };

备注:在 Typescript 中,只要文件存在 import 或 export 关键字,都被视为 module

猜你喜欢

转载自blog.csdn.net/lianghecai52171314/article/details/132382104
今日推荐