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

Error occurred during npm build with Browserify: Module not found

When I run npm build with the following command: "build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js" I encounter the error message below: Error: Cannot find module 'components/maininput.j ...

Creating images or PDFs from HTML with CSS filters: a guide

Looking for someone who has experience creating images or PDFs from HTML code. The HTML contains images with CSS filters such as sepia and grayscale. If you have worked on this type of project before, I would love to hear about your experience. <img cl ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...

transmitting information using dataURL

Hey there! So I've got this code that does a neat little trick - it sends a dataURL to PHP and saves it on the server. In my JS: function addFormText(){ $('body').append('<input type="hidden" name="img_val" id="img_val" value="" /& ...

Maximizing the efficiency of a personalized hook that facilitates data sharing in React

I have developed a unique Custom Hook that looks like the following: import { useEffect, useState } from 'react'; import axios from 'axios'; const myCustomHook = () => { const [countries, setCountries] = useState([]); const [i ...

Using AJAX to query a database and updating a div tag with the submitted form entries

I need assistance in setting up a webpage with an AJAX form. The idea is that upon submission, the form's values will be used to search and query a database for results, which will then be displayed in the same DIV as the form. Any guidance or help o ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

Updating the value in React context does not result in the value being updated

I am in the process of developing a simple routing system where users can either be authenticated or not. I have been using hooks to implement this functionality, but so far, it has not been as successful as I hoped for. authProvider.tsx import React, {Di ...

Angular - the offspring of another element

I'm currently exploring the possibilities of identifying if a clicked element is a child of another using Angular. In jQuery, I would typically use has() for this task, but I'm unsure of the equivalent method in Angular aside from iterating throu ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

Tips on gathering information from an HTML for:

After encountering countless programming obstacles, I believe that the solution to my current issue is likely a simple fix related to syntax. However, despite numerous attempts, I have been unable to resolve it thus far. I recently created a contact form ...

What causes Node.js to be unable to handle requests from Vue.js?

I'm encountering a strange error where Node.js is unable to see the URL address and consistently returns a 404 error. In my Vue.js application, I am making a post request using the axios package when the user clicks a button. The code snippet shows t ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

Creating dynamic forms with JQuery and ReactJS

I have been tasked with creating a form-builder that will be integrated into an application. My role is to focus on designing the front-end using ReactJS. The client’s requirements are very similar to the features of the "jQuery Form-Builder," so I decid ...

Adjust the color of the font within a div element when hovering over it

I've been attempting to modify the text color and add an underline when a user hovers over it. Despite trying various methods, I haven't been successful. I scoured the internet for a solution but couldn't find one that met my specific requi ...

The JavaScript code that added links to the mobile menu on smaller screens is no longer functioning properly

I recently created a website with a mobile navigation menu that should appear when the browser width is less than 1024px. However, I used some JavaScript (with jQuery) to include links to close the menu, but now the site is not displaying these links and t ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...