I was wondering if there is a method to define custom types similar to the Array type in

Is there a way in TypeScript to create a custom type with methods that can access the variable's value directly, similar to how Array methods work without passing the value as a parameter?

For example:

const arrayVar: Array = [1,2,3];

array.find(el => el === 1); 

In this case, the find method has access to the values of the array arrayVar without needing it to be passed as a parameter. I would like to achieve something similar with a custom type, for instance:

const myVar: MyCustomType = 5;

myVar.add(2); // In this case, the return would be 7.

I understand that this could be achieved using classes and functions but then I would have to pass the value of "MyVar" as a parameter (function add(value1, value2), for example). I am looking for a way to directly access the variable's value just like Array does in its methods.

Answer №1

Creating a custom subclass of Number with additional methods:

class CustomNumber extends Number {
  add(number: number) {
    // Explicitly specify that 'this' is an unboxed Number
    return (this as unknown as number) + number;
  }
}

To use this subclass, you can do the following:

const ten = new CustomNumber(10);

The variable ten will be inferred to have type CustomNumber by TypeScript.

Testing the newly added method:

ten.add(5)
> 15

Examining the constructor being used within the Class:

> ten.constructor
[class CustomNumber extends Number]

This approach ensures that the original Number prototype remains unchanged to prevent any potential conflicts.

> 8..constructor
[Function: Number]

or:

> (8).constructor
[Function: Number]

For more information on JavaScript classes, refer to MDN documentation

Potential Pitfalls to Consider

It's important to note that due to the nature of objects vs. regular numbers, comparisons may not behave as expected when using the custom subclass:

> ten === 10
false

For further insights, check out Why should you not use Number as a constructor?

Answer №2

To achieve this functionality, you can extend the Number prototype with a custom method called add:

interface Number {
    add: (val:number) => number;
}

Number.prototype.add = function(val:number): number{ 
    
  return (this as number) + val;
}

var myVal: Number = 5
console.log(myVal.add(7))

Check out this TypeScript Playground link for a demo.

Answer №3

To enhance the functionality of an object at this stage, it is advisable to create a specialized class. This way, you establish a structured area where you can easily add, remove, edit, and reuse code segments.

Although I wrote this in JavaScript, converting it to TypeScript requires minimal effort.

Implementing the Class

class CustomArray {

    constructor() {
        this.arr = [];
    }

   add(value) {
        this.arr.push(value)
    }

    erase(){
        this.arr = [];
    }

    // and so on...

    print(){
        console.log(this.arr)
    }

}

// Using Modules, therefore 'require' will be needed.
module.exports = CustomArray;

The example above represents a basic class structure. Additional functions can always be included to suit specific needs.

FOR IMPLEMENTATION IN DIFFERENT CONTEXTS

const CustomArray = require("./CustomArray");

var arr = new CustomArray();
arr.add(2)
arr.print()

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 to extract an object id from JSON data in Javascript?

I'm currently utilizing the Alpha Vantage API for retrieving stock market information. All data is provided in a specific format: To visualize this data effectively, I need to compile an array or object containing all the dates. Unfortunately, these ...

I need help fetching the selected value instead of the option value in PHP

Can anyone offer some assistance with my issue? I have an HTML and PHP function where I am trying to echo a selected value, not the option value. Here is the desired output: "Patrick or any other name when I select and send the button" <?php ...

most efficient method of sharing information between various angular controllers

I am looking for a way to share form data among multiple controllers before submitting it. Currently, I am using module.value() to store the data as a global variable. var serviceApp = angular.module('sampleservice', [ ]); serviceApp.valu ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

"Encountering a form submission error - requested resource not located

I am currently trying to submit a form to an MVC controller using AJAX, where the controller is expected to take a form collection. I came across this helpful resource on Stack Overflow regarding passing formcollection using ajax call to an action. However ...

SVG.js created a surprising polyline in the svgdom node

My svg.js code generates different SVG strings in the browser (correct) and at node (incorrect with excessive inner SVG elements). Here is my code for the browser: let size = { width: 512, height: 512 }; let entity = { x: 232, y: 162, rx: 137, r ...

Invoke the onclick method using addEventListener

I am attempting to create a basic function that increments a counter when one of my list items is clicked on. However, I keep encountering an error message that says addEventListener is not a function. This is how the HTML looks: <ul class="boxes"&g ...

In order to manage this file type properly, you might require a suitable loader, such as an arrow function within a React

Currently, I am in the process of creating an npm package and have encountered a difficulty with the following code: You may need an appropriate loader to handle this file type. | } | | holenNummerInSchnur = Schnur => { | if (this.beurte ...

Feature similar to Twitter: tap to reveal concealed message

Looking to create a clickable link that reveals hidden text when clicked. It seems like I'm close, but I need help displaying the hidden text. Here's what I have so far. Any guidance would be appreciated! HTML <section id="container"> ...

The VueJs Method has the ability to directly alter a given response

Within my parent component, I am connecting to the backend using a query. Through interactions with the navbar and utilizing my activeView data in the parent component, I trigger the rendering of a new child page upon clicks and pass a prop from the respon ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

Retrieving Values Entered by Users in a Bootstrap Form

Here is the code I have for an input field within Bootstrap: <div class="form-group"> <label for="f2">F</label> <input type="text" class="form-control" name="f2" id="f2&quo ...

What is the process of enabling a concealed input feature?

I have a straightforward script that enables users to input a value into a form. These values are then combined to create a URL, which is used to load a page within an iframe. Everything works fine... but I'm having trouble figuring out how to hide t ...

The JQuery .click event is not functioning properly following the implementation of an AJAX filter

I am encountering an issue with the function below. The function is designed to toggle a div's visibility when clicking on a link with the "show-more" class. It also successfully changes an icon. However, the problem arises when I use an AJAX filter o ...

Conflicting submissions

Can anyone help me with a JavaScript issue I'm facing? On a "submit" event, my code triggers an AJAX call that runs a Python script. The problem is, if one submit event is already in progress and someone else clicks the submit button, I need the AJAX ...

Connecting tabs using R Shiny applications

[Query] library(shiny) server <- function(input, output) { output$iris_type <- renderDataTable({ data.frame(Species=paste0("<a href='#filtered_data'>", unique(iris$Species), "</a>")) }) output$filtered_data <- ren ...

Best practices for utilizing React.Provider in Typescript to manage and refresh user context

I'm currently trying to wrap my head around how Typescript is structured. However, my Typescript React web app is failing to build due to the following error: Type '({ user: { id: any; }; } | Dispatch<SetStateAction<{ user: { id: any; }; }& ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...