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

Disabling specific time slots in the mat select functionality

I have a scenario where I need to display time slots at 30-minute intervals using Mat Select. export const TIME=["12:00 AM","12:30 AM","01:00 AM","01:30 AM","02:00 AM","02:30 AM","03:00 AM&qu ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

Best type for an array of dictionaries

Is there a way to correctly assign the variable r without utilizing any? const d = [{ result: 'aEzRuMA6AtQ6KAql8W9V' }, { result: 'N6mkKsnFJj98MHtYMxIi' }] const result = d.map((r: HERE) => r.result) console.log(result ) // will pr ...

The issue with dispatching actions in TypeScript when using Redux-thunk

As a beginner in TypeScript, I apologize if my question seems silly, but I'll ask anyway: I'm attempting to make an async call getUsersList(), but the issue is that it's not triggering the dispatch (it's not logging "hello"). It worked ...

Utilizing the Redux Connect HOC's wrapped component type in React.RefObject without the need for re-importing

My current setup involves a simple component that is wrapped with react-redux and has a ref with forwardRef: true, demonstrated below: // Button.tsx class Button extends React.Component { // ... } // ... export default connect(mapStateToProps, null, n ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

Instructions for adding a new property dynamically when updating the draft using immer

When looking at the code snippet below, we encounter an error on line 2 stating Property 'newProperty' does not exist on type 'WritableDraft<MyObject>'. TS7053 // data is of type MyObject which until now has only a property myNum ...

The Type {children: Element; } is distinct and does not share any properties with type IntrinsicAttributes

I am encountering an issue in my React application where I am unable to nest components within other components. The error is occurring in both the Header component and the Search component. Specifically, I am receiving the following error in the Header co ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

An issue has been identified in the node_modules/xterm/typings/xterm.d.ts file at line 10, causing an error with code TS1084. The 'reference' directive syntax used

In my project, I have integrated xterm into Angular5. However, I am encountering an error when trying to run the application. Upon executing ng serve, I am facing the following error: ERROR in node_modules/xterm/typings/xterm.d.ts(10,1): error TS1084: In ...

Modifying the value upon saving in Adonis JS model

Using Adonis js I am facing an issue when trying to convert an ISO string to Datetime while saving data (the opposite of serializing DateTime fields to ISO string). I cannot find a way to do this in the model, like I would with a mutator in Laravel. Whene ...

Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done with the useState hook. import { Profile } from "@/types"; import { crea ...

Angular - Using the 'name' attribute with the 'mat-select' element

Currently, I am working on an Angular form that involves the dynamic nature of the userEntitiesRoles array. To ensure smooth functionality, each mat-select tag within the ngFor loop requires a unique name attribute. In order to achieve this, I attempted to ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...

Creating a package exclusively for types on NPM: A step-by-step guide

I'm looking to set up a package (using either a monorepo or NPM) that specifically exports types, allowing me to easily import them into my project. However, I've run into some issues with my current approach. import type { MyType } from '@a ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...