Using a typescript class method as a callback function

I'm currently exploring the use of Typescript with Firebase Functions, aiming to define a class with a method that I want to pass as a callback for exporting the function code. My initial attempt looked like this:

class Bar {
  baz (data) { return data.baz; }
  handler(event) { return this.baz(event.data); }
}

In my index.ts file, I tried the following approach:

functions.pubsub.topic('subscriptions').onPublish(new Bar().handler);

Unfortunately, it resulted in an error stating

cannot access property 'baz' of undefined
, indicating that this is not defined within the handler method.

To address this issue, I attempted using the call method like so:

const barInstance = new Bar()
functions.pubsub.topic('subscriptions').onPublish((event) => barInstance.handler.call(barInstance, event));

Despite trying this workaround, I encountered the same error message. At this point, I am at a loss. Any suggestions would be greatly appreciated.

Answer №1

Below is a potential solution that may be effective... however, it's important to note that without an understanding of your specific onPublish requirements, I have stored the outcome in a variable temporarily as I am unsure of your intended use.

functions.pubsub.topic('subscriptions').onPublish((event) => {
    const outcome = new Bar().processor(event);
});

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

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

Maximizing the efficiency of FIRDatabaseReference for better performance

Do the performance results vary between the following two sets of code snippets? The initial one initializes a database reference and utilizes it for each read and write operation. The second one creates a new database reference for every read and write op ...

Having trouble organizing data using matSort in conjunction with API information

Everything was running smoothly with my mat-table until I tried adding mat-sort as per the official API documentation. Unfortunately, it failed at ngAfterViewInit with the following error message: ERROR TypeError: Cannot set property 'sort' of u ...

Refining the output value in a general return type in Typescript

A problematic situation arises with TypeScript when attempting to type-check a function that returns a specific function based on its arguments. The issue is best illustrated through the following simplified example: type NoiseMaker<T extends Animal> ...

Using jest to simulate a private variable in your code

I am working on unit testing a function that looks like this: export class newClass { private service: ServiceToMock; constructor () { this.service = new ServiceToMock() } callToTest () { this.service.externalCall().then(()=& ...

I'm having trouble retrieving the value from the textbox in my Angular 7 project using TypeScript

I'm currently working with Angular 7 and trying to create a textbox to display its value in an alert. However, I'm facing difficulty in fetching the textbox value in typescript. I would appreciate any guidance on how to proceed with this issue. ...

The two-way binding does not connect the property and event halves to the same target

I am trying to create a two-way binding using reactive forms in Angular. I need to exchange data between the child component and the parent component seamlessly. This is the HTML code for my child component: <input type="text" #name class=&qu ...

Preserving the length information in Typescript while utilizing the .map method

Here is the strategy I am currently implementing: const createMainOrientations = <T extends readonly string[]>( mainOrientationsNames: T ): { [Index in keyof T]: Orientation } => { const temp: Orientation[] = mainOrientationsNames.map( mai ...

A guide on populating a UITableView with multiple cells retrieved from Firebase Firestore Database

Yesterday, I posted a question about loading multiple cells into UITableView from Firebase Realtime Database when the array is stored as a dictionary string. Unfortunately, I didn't receive any help on Stack Overflow. Frustrated with the lack of prog ...

Compatibility issues arise with static properties in three.d.ts when using the most recent version of TypeScript

When compiling three.d.ts (which can be found at this link) using the TypeScript develop branch, an error occurs with the following message: Types of static property 'Utils' of class 'THREE.Shape' and class 'THREE.Path' are i ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

Creating trendy designs with styled components: A guide to styling functional components as children within styled parent components

I am looking to enhance the style of a FC styled element as a child inside another styled element. Check out the sandbox example here const ColorTextContainer = styled.div` font-weight: bold; ${RedBackgroundDiv} { color: white; } `; This resul ...

Using Angular to Make a Request for a Twitter API Access Token

I'm facing some challenges while trying to implement a Twitter Sign-In method for my angular app. The issue seems to be with the initial step itself. I am attempting to make a post request to the request_token API by following the steps outlined at th ...

The expiration time for the email link for Firebase's passwordless login is insufficiently brief

I am currently facing a scenario where I require sending an email containing a Firebase passwordless login link. The website administrator needs to invite a new user to join the site by sending an email, and once the new user clicks on the link, they shoul ...

Using const enums across multiple files with react-scripts-ts

Within our project, we have two distinct subprojects (backend and frontend) that are compiled independently. The frontend utilizes react-scripts-ts, so it is crucial to avoid cross-imports between the two subprojects to maintain the integrity of the transp ...

Guide on building a custom TypeScript type for validating string formats, such as verifying if a string complies with the CSS length property requirements

I am working on a React project that includes a component with a height prop. This prop dictates the CSS properties for the component using the Emotion library. Here is an example: render() { const styles = css` height: ${this.props.height}; `; ...

The TypeScript Generics issue arises when attempting to assign the type '{ result: true }' to type 'T'

Struggling with implementing generic types, I can't seem to make it work properly. It feels like I'm missing something simple. Here's a basic example: // some module type TMainResponse<T> = { data: T; }; interface Foo { func<T ...

What is the process for creating an index signature for a type alias representing a Map in Typescript?

Suppose I have a custom type for a Map as follows: type MyCustomMap = Map<string, number>; Is there any way to add an index signature to this type so that I can set key-value pairs after initializing it? I have been able to achieve this with types ...

Generate Angular component unit tests that involve manipulating the DOM using TypeScript

Currently, I am in the process of developing a UI library in Angular 16. While creating a component like a textarea in my typescript file, I find that manipulating the DOM element at a logical level works smoothly. However, when attempting to write tests, ...