Home > database >  Why typescript translate const to var?
Why typescript translate const to var?

Time:08-06

I worte some code to test typescript how to translate ts -> js.

const printX = (name: string) => console.log(`hello, ${name}!`)
const tt = () => {
 const t1 = 123;
const t2 = 456;

}

I checked the translated js file and it was,

var printX = function (name) { return console.log("hello, ".concat(name, "!")); };
var tt = function () {
    var t1 = 123;
    var t2 = 456;
};

Why Typescript translate from const keyword to var keyword.

I'm wondering if I can make ts translate force const to const.

CodePudding user response:

Set the target in your tsconfig to something above ES5, and then ES6 syntax (such as const) will be preserved.

Modern browsers support all ES6 features, so ES6 is a good choice. You might choose to set a lower target if your code is deployed to older environments, or a higher target if your code is guaranteed to run in newer environments.

The target setting changes which JS features are downleveled and which are left intact. For example, an arrow function () => this will be turned into an equivalent function expression if target is ES5 or lower.

  • Related