Cannot redeclare block-scoped variable ‘name’.
problem
// 报错:Cannot redeclare block-scoped variable 'name'.ts(2451)
// lib.dom.d.ts(27029, 15): 'name' was also declared here.
let name:string = '阳阳';
let age:number = 11;
document.write(`<h1>name=${
name} age=${
age}</h1>`)
reason
默认状态,DOM typings 是全局运行环境,
- 当声明 name时, 与 DOM 中的全局 window 对象下的 name 属性出现了重名。
- 因此,报错:Cannot redeclare block-scoped variable ‘name’.ts(2451)
solution
方法1
- 修改ts配置
- 默认在dom环境,改为es6环境
{
"compilerOptions": {
"lib": [
"es2015" // 默认是 dom 环境下
]
}
}
方法2
- 推荐
- 不修改ts配置
- 将当前物价作为模块声明,就能和全局环境区分
- 在 Typescript 中,只要文件存在 import 或 export 关键字,都被视为 module
let name:string = '阳阳';
let age:number = 11;
document.write(`<h1>name=${
name} age=${
age}</h1>`)
export {
}