0

I know, TypeScript generate JavaScript file with equivalent code.

But, here is a problem, where TypeScript doesn't generate equivalent JavaScript code.

demo.ts

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

demo.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. But, look the JavaScript code it declare myName variable as global variable.

Summary: TypeScript generated JavaScript code's variable always are in global scope (in my case).

So, end of the code the meaning is changed. Why?

2
  • Did you intend your code to result in a reference error? If your run your TS code (which is also valid JS code) as JS, you'll get a reference error because let causes myName to be scoped to the if, so the console.log won't be able to use it. The JS you shared wouldn't have that problem because myName would be hoisted into foo's scope (not the global scope). Commented Jun 14, 2020 at 16:40
  • @TheJim01...Yes, I expect it should give reference error as a result. Because, I declare locale variable in TS code but it act as global variable in JS code. So, obviously browser treat it as a global variable. Which I didn't want. Commented Jun 14, 2020 at 16:54

1 Answer 1

1

i think you are using something like webpack that use babel to transpile code.

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

you need to tell babel your target browser.

ex if you target the last chrome that read let and const the compiled code doesn't change

UPDATE: solved in comment using --target options ex: tsc --target ES2016 file.ts

Sign up to request clarification or add additional context in comments.

13 Comments

Hey, Sandro I'm surrender to you. I don't know what is babel or how to tell about my target browser to babel! Can you tell me more about this?
can you tell me what start code have you use? because there are several way to setup, if your project is new, i think you can configure the browser target in your package.json "browserslist": ['last 1 Chrome versions']
I just create demo.ts file with Sublime Text 3. Where are package.json file?
you can see also how babel transpile code here babeljs.io/…
can you give me another try? :) try this tsc --target ES2016 demo.ts
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.