Exploring Immediately Invoked Function Expressions in TypeScript

I came across an interesting article on self-invoking functions in JavaScript by Minko Gechev. This article teaches us how to create a JavaScript function that calls itself immediately after being initialized. I am curious about how we can achieve this in TypeScript. When I attempted to write the code within export class ComponentName, it did not work. Here's the code snippet I tried:

import {Component, Input} from '@angular/core'

@Component({...})

export class MyComponent{

    @Input() infoes;

    (function(){
        console.log('testing');
    })();
}

The IDE displayed an error stating

unexpected token. a constructor, accessor, method or property was expected
. I believe this error is related to the class concept introduced in TypeScript.

Answer №1

In TypeScript, an IIFE (immediately-invoked function expression) can only be used in places where expressions are allowed. Isolated expressions are not permitted in TypeScript. For example, you cannot have something like `class Foo { 1+1; };`. However, using an IIFE to initialize a field is allowed, as shown in the following example:

class Foo {
    foo: string = (function bar(){
        console.log("testing");
        return "value";
    }());
};

new Foo();

If you run the above code, you will see `testing` printed on the console.


It's also important to note that you cannot define a function inside a class like this:

class Foo {
    function bar(){
        console.log('testing');
    );
}

The correct way to define a method in a class is illustrated below:

class Foo {
    bar(){
        console.log('testing');
    );
}

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

Nx repository encountering module resolution issue

Hey there (and happy new year!), Recently, I utilized a template for a monorepo provided by our organization to migrate an Angular project into the monorepo. Before running npm i, I made sure to add all necessary dependencies. However, after restarting VS ...

Is there a way to transfer data from a custom hook to a component seamlessly?

I am facing an issue with a custom hook that passes parameter data along with fetched data to the Settings component. Inside Settings, I have a hook called setData11 in useEffect and I am trying to set the data passed from useTable but encountering an er ...

Steps for incorporating a new element in Reactjs

While attempting to insert a new element into a React object, I encountered the following issue: const isAdmin = true let schema = { fname: Yup.string().required('Required'), lname: Yup.string().required('Required&apo ...

How to include an authorization header in Angular 2 HTTP PUT request

I'm currently experimenting with using http put in Angular. Here's how my code is set up: const url ='this is my url'; const headers = new Headers({'Authorization': 'this is my token'}); return this.http.put(url, {h ...

Referencing other styled-components in Typescript and React code bases

I'm attempting to replicate this code snippet found on https://styled-components.com/docs/advanced using TypeScript. const Link = styled.a` display: flex; align-items: center; padding: 5px 10px; background: papayawhip; color: palevioletred; ...

Strategies for steering clear of god components in Angular

Currently, I am delving into Angular and following the traditional approach of separating the template, styles, and component into 3 distinct files. The component file houses various functions that serve different purposes: Some functions are activated b ...

Using Ngrx with Angular

When I call dispatch, the data isn't being stored properly. It might be a simple mistake, but as a beginner, I'm having trouble finding it. This is my store setup - User is an interface I created in another file: import { Action } from '@ng ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Looking to customize the scrollbar style within an Angular Material table?

Is there a standard method for customizing the scrollbar design in an Angular Material table similar to the one displayed below? (I am unable to identify any applicable styling attributes through element inspection.) angular-table-issue ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

Prevent Angular from performing change detection on specific @Input properties

Within my Angular component, there are extensive calculations that take place when changes are detected. @Component ( selector: 'my-table', ... 400+ lines of angular template ... ) class MyTable implements OnDestroy, AfterContentInit, On ...

The Angular error message InvalidValueError is thrown when the Map function expects a mapDiv of type HTMLElement, but instead receives a

When attempting to initialize Google Maps, I encountered a particular problem. In this div, I am trying to load the map but consistently receiving the same error message. I attempted to use ngAfterViewInit() in case the view wasn't fully loaded befo ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

The formatting in vscode does not apply to .tsx files

For a while now, I've relied on the Prettier extension in Visual Studio Code for formatting my code. However, since switching to writing React with Typescript, I now need to configure Prettier to format .tsx files accordingly. ...

Troubleshooting the creation of migration paths in NestJS with TypeORM

After diligently studying the NestJS and TypeORM documentation, I have reached a point where I need to start generating migrations. While the migration itself is creating the correct queries, it is not being generated in the desired location. Currently, m ...

Tips for sending just the updated section of the form

I am working with a form group where I map the values from the form to an object type in order to make a request to edit the item. This is my form structure: public companyForm = new FormGroup( { generalInfo: new FormGroup({ name: new ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...

Hovering over the Chart.js tooltip does not display the labels as expected

How can I show the numberValue value as a label on hover over the bar chart? Despite trying various methods, nothing seems to appear when hovering over the bars. Below is the code snippet: getBarChart() { this.http.get(API).subscribe({ next: (d ...

execute a JAR file on a Windows Server

My application is running on a Windows Server using Spring Boot and Angular 2. I am looking for the best way to run the executable jar file in this environment. I have some questions regarding this setup: What is the recommended approach for running the ...