官术网_书友最值得收藏!

Using future JavaScript features

There is another benefit of TypeScript that is important to understand. TypeScript allows us to use some features in JavaScript that haven't yet been adopted by all browsers but still target those browsers. TypeScript achieves this by transpiling the use of these features down to JavaScript code that the targeted browser does support.

As an example, let's look at the exponentiation operator (**) in ES7, which isn't supported in IE. Let's create a file called future.ts and enter the following code:

var threeSquared: number = 3 ** 2;
console.log(threeSquared);

When we run the program in a browser, it should put 9 into the console. Before we do that, let's run the code against the TypeScript compiler to get the transpiled JavaScript. Run the following command in a terminal in the same directory as future.ts:

tsc future

This should generate a file called future.js with the following content:

var threeSquared = Math.pow(3, 2);
console.log(threeSquared);

So, TypeScript converted the exponentiation operator to a call to the Math.pow function, which is supported in IE. To confirm that this works, paste the generated JavaScript code into the console in IE and the output should be 9.

This example is purposely simple but probably not that useful. Async/await, spread operators, rest parameters, and arrow functions are far more useful features that IE doesn't support but TypeScript allows the use of. Don't worry if you don't know what the features in the last sentence are, as we'll cover them when we need them in the book.

主站蜘蛛池模板: 海林市| 平利县| 岳阳县| 丹江口市| 巩留县| 苗栗市| 盘山县| 双鸭山市| 湖南省| 临颍县| 江城| 五家渠市| 淳化县| 奈曼旗| 诸暨市| 平遥县| 瑞丽市| 贵港市| 凭祥市| 淮阳县| 建德市| 娄底市| 珲春市| 苏州市| 斗六市| 彭泽县| 运城市| 丹江口市| 会同县| 鲜城| 平果县| 兰溪市| 青铜峡市| 梁河县| 安新县| 安仁县| 宁南县| 肇源县| 莱西市| 安乡县| 四川省|