Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including:

in Typescript, can Object.prototype function return Sub type instance?

I still couldn't find a solution, so I'm reaching out with a new question.

My goal is to replicate Infix notation in JavaScript/TypeScript for functional programming.

The current approach involves a somewhat unconventional method as shown below:

  const customOperator = op => f =>
    Object.defineProperty(
      Object.prototype, op,
      {
        value: function (a) {
          return f(this)(a)
        },
        enumerable: false,
        configurable: false,
        writable: false
      });

  customOperator('+')
    (a => b => a + b);

  console.log(
    1['+'](2) // <--Infix notation
  );  //3

It's worth noting that this method leads to prototype pollution. While it might be off-topic, any insights on how to avoid this issue would be appreciated.

The main question is related to TypeScript type checking requirements:

customOperator('+')
   ((a: number) => (b: number) => a + b);

Currently, the type-checking fails in TypeScript and doesn't flag any errors in scenarios like:

console.log(
    "foo"['+'](1)
); // "foo1"

console.log(
    1['+']("bar")
); // "1bar"

What would be the correct approach to address this behavior?

TypeScript version used: 3.8.3

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": [
      "esnext",
      "dom"
    ],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": false,
    "declaration": false,
    "noImplicitThis": true
  }
}


SOLVED

const customOperator = (op: string) => (f: Function) =>
    Object.defineProperty(
        Object.prototype, op,
        {
            value: function (a: undefined) {
                return f(this)(a)
            },
            enumerable: false,
            configurable: false,
            writable: false
        });
customOperator('+')
    ((a: number) => (b: number) => a + b);
interface Number {
    '+'(a: number): number;
}

console.log(
    1['+'](2)
); //no error

console.log(
    "foo"['+'](1)
); // type error!!

console.log(
    1['+']("bar")
); // type error!!

using

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": [
      "esnext",
      "dom"
    ],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "declaration": false
  }
}

Answer №1

Considering the unique nature of your task, there may not be a definitive "correct" method to accomplish it. However, could this solution fulfill your requirements?

type OperationFunction = (a: number) => number;

interface Number {
  '+' : OperationFunction;
}

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

Searching for data within an array of objects that contain multiple key-value pairs in the form of arrays: A step-by-step guide

For instance const information = [ { companies: [ {name: 'Yuri'}, {name: 'Boeing'}, {name: 'Laser'}, ], sectors: [ {name: 'Logistic'}, {name: 'Aviati ...

The effectiveness of the javascript widget is hindered by the absence of the meta viewport tag,

As I work on creating a widget to appear at the bottom of webpages, I've encountered a styling issue. The widget's display varies based on whether the webpage includes a specified meta viewport tag or not. <meta name="viewport" content="width ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

What is the best way for Cucumber to move on to the next annotation only after ensuring all async requests from the previous one have finished processing?

I am looking to set up a basic test using Selenium and Cucumber for logging into my web application and confirming that the main page is displayed correctly. Currently, all three tests are returning true even before the page is fully loaded. The issue ar ...

Template displaying multiple polymer variables side by side

Here is the date object I am working with: date = { day: '05' } When I use this code: <div>{{date.day}}</div> It generates the following HTML output: <div>05</div> Everything looks good so far. Now, I want to try th ...

Is there a way for me to receive notifications about errors while piping to gulp browserify?

I am leveraging browserify to utilize npm modules in my front end code, and I use gulp for my build tasks. The setup is functioning smoothly: const browserify = require('gulp-browserify'); gulp.task('js', ['clean'], function ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

When running npm install -g, the package is being installed into a global directory on

For a considerable amount of time, I have been working with node and npm. Now, as I embark on a more extensive project using these tools, I've encountered an issue. Whenever I execute 'sudo npm install -g', the installation is directed to &a ...

Transforming FormData string key names into a Json Object that is easily accessible

Recently, I encountered an issue where my frontend (JS) was sending a request to my backend (Node Typescript) using FormData, which included images. Here is an example of how the data was being sent: https://i.stack.imgur.com/5uARo.png Upon logging the r ...

Can a Bluetooth speaker in a car be utilized for noise cancellation?

While using my ANC earphones one day, I had a thought. The earphones were nearly able to drown out the noise of the car. This got me thinking: could ANC technology be used with car speakers and mobile phone apps? Although it might be challenging to resp ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

Having trouble with retrieving JSONP data? Unsure how to access the information?

Why do I keep getting a -403 error? https://i.stack.imgur.com/T53O9.png However, when I click on the link, I see this: https://i.stack.imgur.com/8GiMo.png How can I retrieve the message? ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

Creating a self-chaining function in JavaScript: A guide

Currently, my goal is to create an Array.prototype function called union( array_to_union ), and then utilize it in the following manner: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... I am aiming for the outcome to be the union of these arrays. ...

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

Issue encountered while executing ./node_modules/.bin/cucumber-js within GitLab CI

I've encountered an issue while setting up a continuous integration build for my node project. Despite the fact that npm run test runs smoothly in my local setup, I am facing an exception in GitLab CI. The error arises from the following test command ...

Error encountered: Mocha - The property '$scope' cannot be read as it is undefined

I encountered an issue: Error: Type Error - Cannot read property '$scope' of undefined at $controller (angular/angular.js:10327:28) at angular-mocks/angular-mocks.js:2221:12 at Context. (src/client/app/peer-review/post-visit.co ...

Encountering an Unhandled Reference Issue while Using JavaScript and AJAX

This is a td element I created using JavaScript: '<td contenteditable="true" onBlur="saveToDatabase(this,s1,' + d.pid + ')" onClick="showEdit(this);">' + d.s1+ '</td>' + I need to pass the value of the saveToData ...

Arranging multiple Label and Input fields in HTML/CSS: How to create a clean and

I'm struggling with HTML and CSS, trying to figure out how to align multiple elements on a page. I've managed to line up all the rows on the page, but for some reason, the labels are appearing above the input fields when I want them to appear be ...