Does the Typescript compiler sometimes skip adding braces?

I am encountering a problem with compiling a specific section of code in my Angular2 project.

public reloadRecords() {
    let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps;
    let data = new Array(this.recordsChartSteps);
    let labels = new Array(this.recordsChartSteps);
    let doneCount = 0;
    let done = new EventEmitter();

    done.subscribe(() => {
        this.recordsChartData[0].data = data;
        this.recordsChartLabels = labels;
    });

    if (this.timeInterval.min == 0)
        this.data.getRecordCount(this.timeInterval.min, this.timeInterval.max).subscribe(count => {
            data[data.length - 1] = count;
            labels[labels.length - 1] = "Total";

            done.emit();
        });
    else for (let i = 0; i < this.recordsChartSteps; i++) {
        let min = this.timeInterval.min + step * i;
        let max = min + step - 1;

        this.data.getRecordCount(min, max)
            .subscribe(count => {
                data[i] = count;
                labels[i] = "De " + new Date(min).toLocaleTimeString() + " à " + new Date(max).toLocaleTimeString();

                if (++doneCount >= this.recordsChartSteps) done.emit();
            }); 
        }
}

The issue I'm facing is with the output from typescript version 2.0.10 (installed via npm).

GlobalViewComponent.prototype.reloadRecords = function () {
    var _this = this;
    var step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps;
    var data = new Array(this.recordsChartSteps);
    var labels = new Array(this.recordsChartSteps);
    var doneCount = 0;
    var done = new core_1.EventEmitter();
    done.subscribe(function () {
        _this.recordsChartData[0].data = data;
        _this.recordsChartLabels = labels;
    });
    if (this.timeInterval.min == 0)
        this.data.getRecordCount(this.timeInterval.min, this.timeInterval.max).subscribe(function (count) {
            data[data.length - 1] = count;
            labels[labels.length - 1] = "Total";
            done.emit();
        });
    else
        var _loop_1 = function(i) {
            var min = this_1.timeInterval.min + step * i;
            var max = min + step - 1;
            this_1.data.getRecordCount(min, max)
                .subscribe(function (count) {
                data[i] = count;
                labels[i] = "De " + new Date(min).toLocaleTimeString() + " à " + new Date(max).toLocaleTimeString();
                if (++doneCount >= _this.recordsChartSteps)
                    done.emit();
            });
        };
        var this_1 = this;
        for (var i = 0; i < this.recordsChartSteps; i++) {
            _loop_1(i);
        }
};

The code is valid Javascript, but it appears that the compiler did not include the necessary brackets for the contents of the else block.

I believe this may be due to omitting the brackets in my Typescript code since the else statement consists of a single block. Should I have included brackets here or is this an issue with the compiler?

In the resulting Javascript, the else block (which is a single for loop in Typescript) translates into multiple statements.

The indentation suggests that the subsequent instructions following the declaration of the _loop_1 variable should also be part of the else block.

To resolve this issue, I could simply add brackets to my Typescript code, which might be considered better practice. Was it my mistake for not including those brackets, or is this a bug in the compiler that should be reported?

Note: English is not my primary language.

Answer №1

Indeed, it appears to be a glitch that needs to be addressed. Here is a simplified example to help illustrate the issue:

var flag = false;
if (flag) for (let j = 0; j < 10; j++) {
  let y = () => j;
}

Interactive Playground.

Essentially, this code should have no effect, but when executed through TypeScript, it throws an error message 'Uncaught TypeError: _loop_1 is not a function'. Your discovery is much appreciated!

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

Enhancing Material UI v4 Themes using TypeScript

I am attempting to implement my own custom palette option in the theme section, but I am struggling with how to do the augmentation part using TypeScript. So far, I have created a file named "material-ui.d.ts" and inside it, I only have: import { PaletteO ...

What is the reason TypeScript does not display an error when assigning a primitive string to an object String?

From my understanding in TypeScript, string is considered as a primitive type while String is an object. Let's take a look at the code snippet below: let s: string = new String("foo"); // ERROR let S: String = "foo"; // OK It's interesting to ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Loading an index.html file using Webpack 3, Typescript, and the file-loader: A step-by-step guide

Attempting to utilize the file-loader and Webpack 3 to load my index.html file is proving to be a challenge. The configuration in my webpack.config.ts file appears as follows: import * as webpack from 'webpack'; const config: webpack.Configura ...

Why is it not possible to convert from any[] to MyType[] in TypeScript?

Within TypeScript, the any type allows for casting to and from any arbitrary type. For example, you can cast from a variable of type any to a variable of type MyArbitraryType like so: var myThing: MyArbitraryType; var anyThing: any; myThing = anyThing; / ...

Utilizing an Observable in an Angular 6 service to ensure proper synchronization with Okta token present in local storage

Within my application, I have implemented third-party authentication to facilitate user login and store a token in their local storage. To enhance the user experience, I am developing a service to cache profile information. This service utilizes the user&a ...

Navigating nested data structures in reactive forms

When performing a POST request, we often create something similar to: const userData = this.userForm.value; Imagine you have the following template: <input type="text" id="userName" formControlName="userName"> <input type="email" id="userEmail" ...

Guide on setting up global typing for AngularJS in your project

I have been working on a project that initially used the deprecated typings method for incorporating Typescript definitions. I now want to transition to using the @types method instead. Currently, we have a typings.json file located in the root of the pro ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...

Error Found: Unexpected Colon (:) in Vue TypeScript File

Important Update: After thorough investigation, it appears that the issue is directly related to the boilerplate being used. As a temporary solution, it is recommended not to extract the TypeScript file but keep it within the .vue file for now. In a sim ...

Testing Ag Grid's column headers using Jest and Angular CLI has proven challenging, as some columns from columnDefs remain elusive

Currently, I am using Jest and Angular Cli testing to validate column headers. In my attempt to replicate the process outlined on https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents, I have encountered an issue where only 2 out ...

Switching Facebook accounts on Firebase

I'm currently working on an Angular2 App that utilizes Firebase as its User system, with authentication providers including Email + Password, Facebook, and Google. One issue I have encountered is that when logging in with Facebook, I am unable to swi ...

Adding Dependencies to a Static Factory in Typescript

I have developed a service in typescript as a Class. Within this class, I have defined a static Factory where dependencies are injected. However, when I compress my application, the dependencies get compressed too, leading to an undefined provider error. ...

How to add Bootstrap and Font Awesome to your Angular project

After attempting to add Bootstrap and Font Awesome to my Angular application, I am encountering issues. I utilized the command npm install --save bootstrap font-awesome and included both libraries in the angular.json file as follows: "styles": ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Strategies for Handling Errors within Observable Subscriptions in Angular

While working with code from themes written in the latest Angular versions and doing research online, I've noticed that many developers neglect error handling when it comes to subscription. My question is: When is it necessary to handle errors in an ...