Linking functions together using callbacks in TypeScript

Having recently read an insightful article on Handling Failure by Vladimir Khorikov, I was inspired to try implementing the concept in TypeScript.

The original C# code example provided a solid foundation, although the technical details were beyond my current understanding.

This is where I currently stand with my implementation:

export class Result<T> {
  success: boolean;
  private error: string | null;
  private _value: T;

  get value(): T {
    if (!this.success) {
      throw new Error('Cannot get value of an error result.');
    }

    return this._value;
  }

  // More code follows...

I find myself struggling to incorporate the chain functions as demonstrated in the example code. While the onSuccess, onFailure, and onBoth functions work seamlessly in the provided code snippet, I am only able to invoke void functions in my own implementation. Passing results to subsequent functions seems to be a challenge.

If anyone could offer guidance or suggestions on how to properly implement this chaining functionality, I would greatly appreciate it.

Answer №1

It appears that you are implementing it in a different way?

The original code is as follows:

public static Result OnSuccess(this Result result, Func<Result> func)
{
    if (result.Failure)
        return result;

    return func();
}

This would be translated to:

onSuccess(fn: () => Result): Result {
    if (this.failure)
        return this;

    return fn();
}

However, your implementation is:

onSuccess(func: Function): Result<T> {
    if (this.success) {
      func();
    }

    return this;
}

Answer №2

Inspired by the concepts presented in a thought-provoking article from Invizi, I have devised a solution.

 onSuccess<U>(fn: (value: T) => U): Result<U> {
    if (this.success) {
      return Result.ok(fn(this._value))
    }

    return Result.fail(this.errorMessage)
  }

This approach allows for flexibility in chaining with specific types, similar to the provided code example.

Result.combine(Rectangle.from(5, 5), Rectangle.from(1, 1))
  .onSuccess(() => {return new User('user')}) // Create new user
  .onSuccess(user => console.log(user.name)) // Print user name

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

Is there a way for me to slice a semicircular shape out of the parent div in order to expose

Does anyone have a solution for removing a half circle div from its parent (footer) to reveal the background underneath? I've searched for canvas and jQuery solutions but haven't found anything that works. I am aiming to achieve something simil ...

Improving the innerHTML syntax

I am looking for the correct syntax to add content to an element using innerHTML. Here is an example that isn't working as expected: openNewWindow: function(content) { popupWin = window.open(content, 'open_window', 'menubar, ...

Determine the character's position in an input field by tracking mouse movements

I am in need of a way to determine the position of a character in an input field based on mouse movement. For example, if the input field contains the value 'abcde' and I hover my mouse over the character 'a', the position should be ...

Prevent global CSS from being overridden in a production environment for a React Next.js application

Being new to REACT-NEXT and coming from an Angular background, I am struggling with fixing this issue. Here is the element I am using from another resource: import example-custom-ele-parent, {example-custom-ele-child} from 'custom-tags/example-custom& ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

How do I adjust the amount of a product in my Django ecommerce store?

There seems to be an issue where the quantity is only being changed in the first product, even if I click on the arrow of the second product. The changes are reflected in the quantity of the first product instead. cart.js var changeQ = document.getElements ...

Elements are unresponsive to scrolling inputs

My Ionic 2 input elements are not scrolling to the top when the keyboard is shown. I've tried everything I could find on Google, making sure the keyboard disable scroll is set to false. However, I still can't figure out what's causing the sc ...

What is the best way to calculate the number of items in your mongoose reference with a specific field?

I am trying to calculate the number of active Workers that belong to a specific company. Here is an example scenario: const workerSchema = new Schema( { userId: { type: Types.ObjectId, ref: 'User', ...

Manage an error request with unique parameters

I recently made a GET request using axios in my web application: axios({ method: 'get', url: "example.com", params:{ _id: "anId" } }) .th ...

Enhance your AngularJS application with advanced security features and implement a local storage

I have implemented an AngularJS application that utilizes angular ui-router for routing. Despite my efforts to enhance security, I encountered some challenges: To manage user authentication, I store tokens and user roles in local storage, redirecting ...

Tips for setting up Nginx with Node.js on a Windows operating system

I am looking to set up Nginx on my Windows machine in order to run two node applications. Can anyone provide guidance on how to accomplish this? I have attempted to download Nginx 1.6.3, but have had trouble finding instructions specifically for running i ...

Connectivity issue: Socket.io fails to register user upon connection

Upon connecting to the page, I expect to see the message 'a user connected' printed on the command line using node.js. However, this message is not being displayed, indicating that the user's visit to the page is not being registered (all ac ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

What is the best way to set a CSS background using vue-cli 3?

What is the process for setting a CSS background in vue-cli 3? I have set my vue.config.js like this. Is publicPath properly configured? JavaScript const path = require("path"); module.exports = { devServer: { port: 8081, overlay: { warni ...

What is the process for dynamically altering the source file of VueRouter?

Hello, I am working on a project that involves multiple roles using VueJs and Laravel. Laravel is used as the back-end while Vuejs serves as the front-end. The project has three different roles: User, Modirator, and Editor. Here is a snippet of my code ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...