Tips for integrating an arrow function as a property in a functional programming approach using JavaScript or TypeScript

Suppose I were to create a constructor for a functional class with TypeA as an argument, and TypeB representing the type of the class itself. In such cases, I can implement it using:

functionName(argument: TypeA): TypeB {
    this.property = argument;
    return this;
  }

However, I am unable to achieve the same result with:

property: (argument: TypeA): TypeB => ({
    property: argument,
    ...
  })

The reason behind this limitation is the distinction in how the keyword this behaves between arrow functions and regular functions.

So, how can I replicate the behavior of the first case using an arrow function?

For example:

import personConst from './personConst';
// const personConst: { [key: string]: UnitBase } = {
//   brah: {
//     name: "Thomas",
//     age: 25,
//     gender: "male"
//   },
//   hoge: {
//     name: "Sarah",
//     age: 29,
//     gender: "female"
//   },
//   ...
// }

import { PersonBase } from './PersonBase';
// export interface UnitBase {
//   name: string;
//   age: number;
//   gender: string;
// }


interface Person extends PersonBase {
  income: number;
  zip: number;
  setIncome(newIncome: number): this;
  setZip(newZip: number): this;
}

const person = (key: string): Person => ({
  income: 50000,
  zip: 50000,
  setIncome: (newHp: number): Person => ({
    income: newIncome,
    ... // Error: Expression expected.
  }),
  setZip(newZip: number): Person {
    this.zip = newZip;
    return this; // OK
  },
  ...personConst[key]
});

export default person;

Answer №1

It seems like there may be some confusion regarding your question. If you intend to utilize the this context, it is recommended not to directly use an arrow function such as x => y. Instead, opt for the more detailed anonymous function syntax like (function(x){ return y }):

const person = (key: string): Person => ({
  income: 50000,
  zip: 50000,
  setIncome: function(newIncome: number): Person { // anonymous function
    return {
      ...this, 
      income: newIncome
    };
  },
  setZip(newZip: number): Person {
    this.zip = newZip;
    return this; // OK
  },
  ...personConst[key]
});

This should hopefully meet your requirements:

const thomas = person("brah");

console.log(thomas.zip); // 50000
thomas.setZip(10301);
console.log(thomas.zip); // 10301

console.log(thomas.income); // 50000
thomas.setIncome(100000);
console.log(thomas.income); // 50000
const newThomas = thomas.setIncome(100000);
console.log(newThomas.income); // 100000

Without further details from your side, it's hard to determine if this solution aligns with what you need. In any case, feel free to give it a try and good luck!

Link to code

Answer №2

Avoid integrating fat arrow in all scenarios. It is typically utilized: - By utilizing fat arrow (=>), we eliminate the requirement to use the 'function' keyword. It creates an anonymous function. - To circumvent bindings in constructor, you can employ ( =>). - In functions such as doSomething(){ }, fat arrow cannot be used here. However, for instance: function (){ }, lambda can be utilized instead.

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 might be the reason for npm live-server to cease detecting file updates?

Everything was working perfectly on my system, but now I'm facing an issue. I have the live-server version 0.8.1 installed globally. npm install live-server -g However, when I start it, I no longer see the "Live reload enabled." message in the brow ...

How can you utilize Javascript to retrieve an element by its inner text within the HTML tags?

As a novice, I have been struggling to find the solution to my question even after extensive searching. In the scenario at hand, I am specifically interested in locating the following element: <a href="bla" onclick="dah">some text here</a> I ...

I'm having trouble understanding why my data does not appear even though there is space allocated for it automatically

I'm facing an issue with my code that is supposed to populate a table with dynamic content using react and ant.design. Everything seems to be working fine, but the actual content is not displaying - only the space for it is created. What's happe ...

Best practices for working with Angular, Laravel 4, and managing MySQL databases

I have recently started working with Angular and have some experience using Laravel 4. I am currently developing an application that allows users to edit on the go while also saving to a MySQL database. Originally, my plan was to use Angular for real-time ...

Tips on incorporating "get_template_directory_uri" into a JavaScript function

I am currently working on my WordPress PHP file code, where I have included a JavaScript snippet to display names and images from a query. While the names are being displayed correctly, I am encountering an issue with the images not showing up. After tryi ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

in the matchMedia addListener callback function, you can pass an argument

While working on a plugin that involves toggling certain behaviors on and off using matchMedia functions, I encountered an issue with passing arguments to my callback function. Whenever I try to pass an argument to the callback function, it returns as unde ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

Accessing Google Analytics with a single OAuth token using the JavaScript API: A step-by-step guide

I'm currently developing a webpage for exclusive users to view shared Google Analytics data. I have managed to obtain an OAuth token for the account housing this data using JavaScript, but sadly it expires in just 1 hour. Is there a way to utilize th ...

Looking up a destination with the Google Places API

My dilemma lies in dealing with an array of place names such as 'Hazrat Nizamuddin Railway Station, New Delhi, Delhi, India' and similar variations. These variations serve as alternative names for the same location, adding complexity to my task. ...

How can one determine if a DOM element has been generated dynamically?

Some of the content on this page is dynamically created after an ajax request, while other content was pre-loaded when the page refreshed. When I click on an anchor tag, I need to know if it was created dynamically or not. I did manage to solve this issu ...

Node.js equivalent of hash_hmac

I am facing an issue while trying to sign the URL in a Node.js application similar to how it is done in my PHP app. In PHP, I use the following code to sign the URL: private static function __getHash($string) { return hash_hmac('sha1', $stri ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Flawless Carousel - Flipping the Sequence

I am currently implementing Slick Carousel on a website that I am working on. One challenge I am encountering is trying to get the "slider-nav" to move in the opposite direction than it normally does. For instance, at the moment, the order goes like this ...

Switch out HTML dynamically using JavaScript/JQuery, embracing the principles of DRY coding

As a newcomer to front-end development, one issue I frequently encounter is avoiding repetition when dynamically generating HTML using JS/jQuery. Imagine you have a DOM object that has various states. Typically, all you need to do with JS is switch betwee ...

A guide on navigating through an array nested within an object

I have been diving into the world of ReactJS, experimenting with different APIs to fetch and manipulate data. Currently, I am working with the Flickr API which returns data structured as "An array inside an object". { "photos": { "page": 1, "page ...

Query regarding timing in JavaScript

I recently started learning JavaScript and I am facing a challenge with running a check to determine if it is daylight. Currently, I am using Yahoo's weather API to retrieve information about sunrise and sunset times. The issue I have encountered is h ...

What are the steps to integrate jQuery into an Angular 8 application?

I am currently working on an application that relies on SignalR for communication with a desktop application. In order to make use of SignalR, I include jQuery in my .ts file. However, after migrating from Angular 7 to Angular 8, it appears that this setup ...

Is it possible to configure npm to publish to an organization different from the one automatically detected from package.json?

We are looking to implement a process in our open source project where all Pull Requests will be published to npm using CI/CD. To reduce the potential for supply chain attacks, we aim to deploy to a separate organization. Can this be achieved without makin ...