What does Typescript compile when aiming for ES5 / ES3?

I'm currently grappling with the nuances of when the Typescript compiler decides to transpile code in order to align it with my designated target ECMAScript version (ES5 or ES3).

As an example, TSC has no problem transpiling for(var int of intArray); however, it fails to transpile Number.isInteger() (which is considered an ES6 feature, as per information from w3schools).

Number.isInteger() lacks support in IE < 11.0, presenting an issue. Surprisingly, Visual Studio (including VS Code) does not alert about incompatibility nor does it undergo transpilation.

What criteria determines what gets transpiled and what doesn't? I initially assumed that everything would be transpiled so that I wouldn't have to monitor issues like this, but apparently, that's not the reality.

Answer №1

TypeScript transpiles code to ensure compatibility with the specified target environment, but it does not automatically polyfill missing functionality. Essentially, TypeScript transforms any syntax that is invalid in the target environment into valid syntax. For instance, if you use the `class` keyword with a target set to `ES5`, TypeScript will transpile it like this:

class Greeter {
}

Would be transformed into:

var Greeter = /** @class */ (function () {
    function Greeter() {
    }
    return Greeter;
}());

(You can experiment further with TypeScript on its online playground.)

However, when it comes to features that are missing in the target environment, such as `Number.isInteger()` in ES5, you need to manually apply polyfills. This means adding extra code or libraries to fill in those gaps. You can use tools like babel-polyfill or services like polyfill.io for this purpose.

Note: The `lib` option in TypeScript does not handle polyfills; it simply informs TypeScript to check types based on specific ECMAScript versions. Polyfilling remains your responsibility for ensuring compatibility across different browsers. Failure to include necessary `lib`s may lead to TypeScript errors regarding missing features like `Number.isInteger()`.

While there isn't an exhaustive list of what TypeScript transpiles, you can find information on TypeScript and polyfills with `core-js` in this table: here. For additional insights on polyfills and transpilation, check out this resource here.

Answer №2

The compiler's functionality is determined by the specific lib you designate for it to use.
You can control which lib the compiler utilizes in two ways: through the target and lib compiler options.

As described in the link above:

If --lib is not specified, a default library will be included. The default libraries injected are:
► For --target ES5: DOM,ES5,ScriptHost
► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

All the different libs can be found as part of the project.

If you're aiming at es3 or es5, then features like Number.isInteger() cannot be used since it's considered an exclusive feature of es6.
If you have a polyfill available, you can still target es5 by including the es6 lib:

--target es5 --lib DOM,ES6,ScriptHost

Alternatively, you can manually insert the definition from lib.es6.d.ts:

interface NumberConstructor {
    isInteger(number: number): boolean;
}

The reason behind being able to utilize keywords like let, const, for/of regardless of the target is that the compiler has mechanisms in place to generate equivalent code even when the feature isn't supported for the selected target.

For instance:

const arr = [1, 2, 3];
for (let num of arr) {}

Will be compiled to:

var arr = [1, 2, 3];
for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) {
    var num = arr_1[_i];
}

If no target is specified.
As seen, const and let get converted into var, and for/in turns into a standard for loop.

Number.isInteger() presents a different scenario, being a feature absent in certain targets such as Promise and 'Symbol`.
The burden of adding the polyfill rests on you, alongside informing the compiler about its presence.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

The form will not appear if there is no data bound to it

Can anyone help me with displaying the form even when the data is empty in my template? <form class="nobottommargin" *ngIf="details" [formGroup]="form" (ngSubmit)="onSubmit(form.value)" name="template-contactform"> <div class="col-sm-12 nopad ...

Supply type Parameters<T> to a function with a variable number of arguments

I am interested in utilizing the following function: declare function foo(...args: any): Promise<string>; The function foo is a pre-defined javascript 3rd party API call that can accept a wide range of parameters. The objective is to present a coll ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

Restrict or define the acceptable values for a key within an interface

In search of defining an interface that allows for specific range of values for the key. Consider this example: interface ComparisonOperator { [operator: string]: [string, string | number]; } The key can take on values such as >, >=, !=, and so ...

What could be the reason it's not functioning as expected? Maybe something to do with T extending a Record with symbols mapped

type Check<S extends Record<unique, unknown>> = S; type Output = Check<{ b: number; }>; By defining S extends Record<unique, unknown>, the Check function only accepts objects with unique keys. So why does Check<{b:number}> ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

Utilizing TypeScript's generic constraints for multiple primitive data types

Consider the following function: myFunc(object: string | null): string | null {} The desired behavior for this function is to return type string when the object parameter is of type string, and return type string | null when the object parameter is of ty ...

Can a TypeScript generic version of the Y-combinator be successfully executed?

Here is an interesting JavaScript implementation of the Y-combinator: const Y = g => (x => g(x(x)))(x => g(x(x))) //or const Y = f => { const g = x => f(x(x)) return g(g) } I've been thinking, could it be possible to create a TypeS ...

What exactly is an npm "modular construction" and what is the process for setting it up?

I am aiming to integrate sortablejs's MultiDrag feature with Vuejs2 and Typescript. The official documentation states: MultiDrag is a plugin for SortableJS, but it may not be included in all of Sortable's builds. It comes pre-installed in the ...

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples. function (times: Array<number> | Array<[number, number]>) { if (Array.isArray(times[0]) ...

Issue on Ionic serve: Unable to locate module '@angular/compiler-cli/ngcc'

i encountered a problem after installing a cordova plugin and running "npm audit fix". When attempting to serve my app, an error message pops up: [ng] An unhandled exception occurred: Cannot find module '@angular/compiler-cli/ngcc' [ng] See ...

Obtain the firebase object using Angular framework

Hey there, I've been working on retrieving a Firebase object using Angular and have successfully achieved that. However, I'm now faced with the challenge of how to navigate deeper into the data that is being returned (check out the images linked ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

The error message "TypeScript is showing 'yield not assignable' error when using Apollo GraphQL with node-fetch

Currently, I am in the process of implementing schema stitching within a NodeJS/Apollo/GraphQL project that I am actively developing. The implementation is done using TypeScript. The code snippet is as follows: import { makeRemoteExecutableSchema, ...

What is the best way to implement a timer using hooks in React?

Just getting started with React! I began my journey last week ;) My first task is to build a timer that includes a reset feature and can count seconds. While the reset function is functioning properly, the timer isn't. Can anyone suggest the best ap ...