Troubleshooting the issue of object method definition failure in TypeScript

Why am I encountering an error when trying to define an object method like this:

export class Helper {
    function add(x: number, y: number): number {
        return x + y;
    }
}

The error message reads as follows:

Unexpected token. A constructor, method, accessor, or property was expected.

I have referenced the example on https://www.typescriptlang.org/docs/handbook/functions.html, but despite following it closely, I still encounter this issue. Interestingly, removing the function keyword resolves the error, although this seems to contradict the information provided in the official TypeScript documentation.

Answer №1

Avoid using functions inside a class! Update to the following:

export class Helper {
    add(x: number, y: number): number {
        return x + y;
    }
}

In TypeScript, it is recommended not to use functions as members of a class. Instead, convert it to a method!

According to mattjes, consider making the method static...

export class Helper {
    static add(x: number, y: number): number {
        return x + y;
    }
}

Helper.add(1, 2)

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

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

Attention: React is unable to identify the X attribute on a DOM component

Encountering an error while attempting to pass props in a basic manner. interface Props extends Omit<React.HTMLAttributes<HTMLElement>, 'color'>, ChakraProps { handleMoveAll: () => void } export const MyWrapper: FC<Props> ...

Build a module that includes both components and services

Currently, I am working on an Ionic 3 application and found the need for an accordion component similar to NgBootstrap's. Unfortunately, the Ionic framework does not offer such a component. This led me to take on the challenge of creating one myself, ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

The evaluation of the Angular getter takes place prior to the constructor being executed

constructor( private readonly authService: SocialAuthService, private readonly authS: AuthService, private readonly loginS: LoginService, private readonly router: Router, private readonly formBuilder: FormBuilder, ) { alert(' ...

Guide on Implementing a New Method into a React Functional Component

I have a component that looks like this: const Abc: React.FC<AbcTypes> = ({...}) => {...} Abc.getLayout = () => {...} I am not sure how to properly define or extend the method getLayout on the Abc component in TypeScript? ...

Having trouble locating a module while utilizing custom import paths in multiple tsconfigs

My current project involves the use of multiple tsconfig.json files. I'm aiming to streamline all imports, but oddly enough, shortened imports aren't functioning correctly in a specific situation. Here's how my project is structured: foo/ ...

A function that accepts a type parameter and returns an instance of that specific type

My goal is to implement a factory method for all my Axios API classes that are generated by the OpenAPI generator. The Open-API tool creates a BaseAPI class with a constructor, and then generates several API classes that extend this BaseAPI based on my Ba ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

Using *ngFor to iterate through a nested collection in an Angular 2 application

I'm currently working on a challenge involving drilling down to iterate over an array within another collection of arrays within an Angular 2 application. To start off, I have set up my component to subscribe to an observable in the ngOnInit lifecycle ...

Unlock the power of the multiselect dropdown component in MUI with direct access

I'm intrigued by the multi-select capabilities of the MUI Select component when using the multiple=true option. However, rather than having a traditional dropdown menu, I want to integrate the selection options directly into a div on the page. I prefe ...

Exploring React State Management: Leveraging the Context API as a centralized store for

Currently, I am developing a React web application using TypeScript. To enhance the State Management, I decided to implement React Hooks and Context API by following a concise tutorial that I came across here. Despite diligently following the tutorial, my ...

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

Troubleshooting an Angular application in Intellij using Chrome on a Windows operating system

I've been searching for a long time for a way to debug an Angular app in IntelliJ using Chrome on Windows. So far, I have not been successful in attaching a debugger to Chrome. I have tried launching Chrome with --remote-debugging-port=9222 and numer ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: https://i.sstatic.net/kxsSD.png But this is the look I want to achieve: https://i.sstatic.net/kJC2m.png Below is the code ...

Having trouble retrieving spot price using Uniswap SDK due to a transaction error LOK

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( immutables.token0, immutables.token1, immutables.fee, amountIn, 0 ) I set up a pool on Uniswap V3 for two ERC20 dummy tokens by using the createPool() met ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

Is it possible to transform a personalized typescript component into an HTMLElement within the Angular framework?

Suppose I have a customized component named 'my-component' in Angular. Is there a method to transform this component into a HTMLElement so it can be passed to a function that requires a HTMLElement as an argument? I am aware that the HTMLElemen ...