typescriptlang.org 主页上列出的 Typescript 的主要优点之一是能够编写“最先进的 Javascript”,可以编译到任何 ES3 或更新的目标。我可以在 Typescript 中使用许多 ES6 函数,包括let
and const
、箭头函数、解构、模板文字等。
我试图理解为什么某些 ES6 功能在 Typescript 中不可用。是否有路线图指定何时将某些 ES6 功能添加到 Typescript,或者解释为什么它们可能不会添加?
例如,尝试在 Typescript 中使用 String.includes 会导致错误,并且生成的 javascript 不会被转译,并且在不支持该方法的浏览器中会失败。
Opera 中的转译版本(在 tsconfig.json 中将目标设置为 ES5)失败:
let homer = "homer simpson";
if(homer.includes("homer")) {
alert("Yes! We have a homer!");
}
我可以添加我自己的 polyfill,它可以工作:
// Polyfill for .includes
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
let homer = "homer simpson";
if(homer.includes("homer")) {
alert("Yes! We have a homer!");
}
在 Typescript 中实现的 ES6 特性的几个示例
模板文字
let myDiv = `
<div>
<h2>I am part of a template literal.</h2>
</div>
`
转译为
var myDiv = "\n <div>\n <h2>I am part of a template literal.</h2>\n </div>\n";
解构
let [a,b] = [1,2,3];
转译为
var _a = [1, 2, 3], a = _a[0], b = _a[1];
箭头函数
const arrsq = [1,2,3];
const squares = arrsq.map(x => x*x);
转译为
var arrsq = [1, 2, 3];
var squares = arrsq.map(function (x) { return x * x; });