An error is thrown when a try/catch block is placed inside a closure

An issue arises when attempting to compile this simple try/catch block within a closure using TypeScript:

type TryCatchFn = (args: any, context: any) => void;

function try_catch(fn: TryCatchFn): TryCatchFn {
    return (args, context) => void {
        try {
            throw new Error('Something bad happened');
        } catch (e) {
            console.log(e);
        }
    }
}

The compiler error message reads as follows:

data/src/cloud_scripts.ts:12:7 - error TS1005: ':' expected.

12      try {
            ~


data/src/cloud_scripts.ts:13:10 - error TS1005: ':' expected.

13              throw new Error('Something bad happened');
                      ~~~


data/src/cloud_scripts.ts:13:45 - error TS1005: ',' expected.

13              throw new Error('Something bad happened');
                                                         ~


data/src/cloud_scripts.ts:14:5 - error TS1005: ',' expected.

14      } catch (e) {
          ~~~~~

However, when the code is adjusted to remove the call to the fn function, the compilation succeeds without errors:

type TryCatchFn = (args: any, context: any) => void;

function try_catch(fn: TryCatchFn): void {
    try {
        throw new Error('Something bad happened');
    } catch (e) {
        console.log(e);
    }
}

The revised version above sacrifices functionality for the sake of successful compilation. It poses the question of what might be going wrong in the initial implementation.

Answer №1

The declaration of the return type in an arrow function should be placed after the parameter list and before the => symbol:

type TryCatchFn = (args: any, context: any) => void;

function try_catch(fn: TryCatchFn): TryCatchFn {
    return (args, context): void => {
        try {
            throw new Error('Encountered an error');
        } catch (e) {
            console.log(e);
        }
    }
}

Alternatively, you can omit the return type altogether:

function try_catch(fn: TryCatchFn): TryCatchFn {
    return (args, context) => {
        try {
            throw new Error('Encountered an error');
        } catch (e) {
            console.log(e);
        }
    }
}

Answer №2

When you are crafting your code like this:

return (args, context) => void { ... }

this syntax is actually forming an arrow function with an expression body. The void operator assesses the succeeding expression and then discards its result, making it a function that returns undefined. In this scenario, the expression happens to be an object literal, where the usage of try isn't permitted.

If the void is omitted,

return (args, context) => { ... }

you will get an arrow function with a block statement body instead. Here, your try statement will operate as expected. If nothing needs to be returned from the block, you aren't obliged to specify the return type explicitly, although you have the option:

return (args, context): void => { ... }

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

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...

Classify the array types based on their indexes within the map

Is there a way to efficiently access elements in TypeScript using a map with the correct type? When attempting this, an error is thrown due to the type from the map being number | string type Tuple = [number, number, string]; const y: Tuple = [1, 2, &apos ...

In ReactJS, the way to submit a form using OnChange is by utilizing the

Is there a way to submit a form using Onchange without a button? I need to fire the form but can't insert routes as it's a component for multiple clients. My project is built using react hook forms. const handleChange = (e: any) => { c ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

The class variable cannot access the Angular Http response returned by the service

I have a Typescript application built with Angular 2. In this application, I need to retrieve Build Artifacts from a Jenkins server using the Jenkins Rest API. The Build Artifact contains a text file that I want to read from. I am making use of Angular&apo ...

Accessing a variable within a function in Angular

Recently I started working with Angular and encountered an issue while trying to access a variable inside a function. Below is the code snippet that's causing me trouble: mergeImages() { var imgurl; var canvas: HTMLCanvasElement = this.canv ...

Having trouble viewing the value of request headers in Firebase?

Here is my code snippet: var headers = new Headers(); headers.append("bunny", "test"); headers.append("rabbit", "jump"); fetch("blahurl.com/someservice", {headers:headers}) When it comes to handling the request on Firebase: export const listener = funct ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Adding a second interface to a Prop in Typescript React: a step-by-step guide

import { ReactNode, DetailedHTMLProps, FormHTMLAttributes } from "react"; import { FieldValues, SubmitHandler, useForm, UseFormReturn, } from "react-hook-form"; // I am looking to incorporate the DetailedHTMLProps<FormHTMLAt ...

The error message "TypeError: router.back is not a function" indicates that

Testing out the back route navigation in next.js and encountering an error during the test: https://i.sstatic.net/O6Nax.png The function for going back: const router = useRouter(); const handleClick = useCallback(() => { if (router ...

Guide to incorporating Moengage into Node.js APIs for delivering email notifications based on user interactions

How can Moengage be integrated into Node Js APIs for sending notifications to users based on user events? I have reviewed the Moengage API documentation but did not find relevant information on integrating Moengage with Node Js APIs. Is there a step-by-s ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

Changes made in the Firestore console do not automatically activate the snapshotChanges subscription

I'm facing an issue with subscribing to a document in Firestore using AngularFire. Even after making changes to the document through the Firestore console, I don't see any updates reflected in the pulled data, even after refreshing locally. The D ...

Error: Unable to access 'nativeElement' property from undefined object when trying to read HTML element in Angular with Jasmine testing

There is a failure in the below case, while the same scenario passes in another location. it('login labels', () => { const terms = fixture.nativeElement as HTMLElement; expect(terms.querySelector('#LoginUsernameLabel')?.tex ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

Utilizing Firebase 3 with Ionic 2 and cordova-plugin-camera for seamless file uploading

I have been attempting to upload images to Firebase storage using the cordova-plugin-camera but have not been successful: Below is the code I have been using: let options:any = { quality : 100, destinationType : Camera.DestinationType.DATA_URL, ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...