2017-09-15 48 views
1

我想在我的打字稿代码中声明名为name的新变量。我只有一行代码。为什么我得到错误无法在TypeScript中重新声明块范围变量'name'

var name:string = "John"; 

但遇到错误

PS D:\TypeScript> tsc test.ts 
C:/Users/Users/AppData/Roaming/npm/node_modules/typescript/lib/lib.d.ts(18568,15): error TS2451: Cannot re 
declare block-scoped variable 'name'. 
test.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'name'. 

这是什么错误背后的原因是什么?

cannot redeclare block-scoped variable 'name'

cannot redeclare block-scoped variable 'name'

+0

出现此错误的原因是全局范围中已存在变量'name'。 – Adelin

回答

2

默认情况下,打字稿使用DOM分型,为全球执行环境,如果你改变你的变数名称存在于DOM

全局窗口上的name属性到name1,它不会告诉你这个错误。但是,typescript建议使用ES6语法,因此您的IDE可能会建议您使用const/let来代替。

看看这个链接 https://github.com/Microsoft/vscode/issues/22436

希望这有助于。

快乐学习

+0

解决方法是将其定义为:'export var name:string =“John”;' – Adelin

+0

@Adelin谢谢:) –

+0

@Adelin - 你是对的:) – Vatsal

1

要解决这个问题,你可以简单的有出口没有出口的语句。换句话说,只需写

export {}; 

某处在您的文件的顶层。

相关问题