One of the main benefits of Typescript listed on typescriptlang.org's homepage is the ability to write "State of the Art Javascript" that will compile to any ES3 or newer target. I can use many ES6 functions in Typescript, including let
and const
, arrow functions, destructuring, template literals, etc., etc.
I'm trying to understand why certain ES6 features are not available in Typescript. Is there a roadmap specifying when certain ES6 features will be added to Typescript, or an explanation regarding why they might not be?
For example, trying to use String.includes in Typescript causes an error, and the resulting javascript is not transpiled and fails in browsers that don't support the method.
The transpiled version (with target set to ES5 in tsconfig.json) of this fails in Opera:
let homer = "homer simpson";
if(homer.includes("homer")) {
alert("Yes! We have a homer!");
}
I can add my own polyfill and it works:
// 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!");
}
A few examples of ES6 features that are implemented in Typescript
Template Literal
let myDiv = `
<div>
<h2>I am part of a template literal.</h2>
</div>
`
transpiles to
var myDiv = "\n <div>\n <h2>I am part of a template literal.</h2>\n </div>\n";
Destructuring
let [a,b] = [1,2,3];
transpiles to
var _a = [1, 2, 3], a = _a[0], b = _a[1];
Arrow Functions
const arrsq = [1,2,3];
const squares = arrsq.map(x => x*x);
transpiles to
var arrsq = [1, 2, 3];
var squares = arrsq.map(function (x) { return x * x; });