简体   繁体   English

TypeScript 中的变量声明错误

[英]Error with variable declaration in TypeScript

I know, TypeScript generate JavaScript file with equivalent code.我知道,TypeScript 生成具有等效代码的 JavaScript 文件。

But, here is a problem, where TypeScript doesn't generate equivalent JavaScript code .但是,这里有一个问题, TypeScript 不会生成等效的 JavaScript 代码

demo.ts演示.ts

function foo()
{
    if(1)
    {
        let myName = "Raktim";
    }
    console.log(myName);
}
foo();

demo.js演示.js

function foo() {
    if (1) {
        var myName = "Raktim";
    }
    console.log(myName);
}
foo();

See above, I declared a locale variable myName in the demo.ts file.见上文,我在demo.ts文件中声明了一个语言环境变量myName But, look the JavaScript code it declare myName variable as global variable.但是,看看 JavaScript 代码,它将myName变量声明为全局变量。

Summary: TypeScript generated JavaScript code's variable always are in global scope (in my case).摘要: TypeScript 生成的 JavaScript 代码的变量始终位于全局 scope 中(在我的情况下)。

So, end of the code the meaning is changed.因此,代码末尾的含义发生了变化。 Why?为什么?

i think you are using something like webpack that use babel to transpile code.我认为您正在使用 webpack 之类的东西,它使用 babel 来转译代码。

https://babeljs.io/docs/en/babel-preset-env https://babeljs.io/docs/en/babel-preset-env

you need to tell babel your target browser.你需要告诉 babel 你的目标浏览器。

ex if you target the last chrome that read let and const the compiled code doesn't change例如,如果您以最后一个读取 let 和 const 的 chrome 为目标,则编译后的代码不会改变

UPDATE: solved in comment using --target options ex: tsc --target ES2016 file.ts更新:使用 --target 选项在评论中解决,例如:tsc --target ES2016 file.ts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM