A guide on creating a concatenation function using TypeScript

Looking for a way in Typescript to define an interface Calculator that allows for concatenation capabilities?

interface Calculator {
    ...
}
 
let calcu: Calculator;
calcu(2).multiply(5).add(1)

I attempted the following:

interface Calculator {
  (num: number): Calculator;
  multiply(num: number): Calculator;
  add(num: number): Calculator;
}

Encountered an error stating that calcu is not instantiated:

Variable 'calcu' is used before being assigned

My question now is how can I define the interface Calculator and successfully instantiate calcu.

Answer №1

Interfaces serve to outline the structure of something; it is advisable to create a class that can be initialized with new.

For example:

class Calculator
{
    constructor(public num: number) { }
    multiply(num: number)
    {
        this.num *= num;

        return this;
    }
    add(num: number)
    {
        this.num += num;

        return this;
    }
}

const calcu = new Calculator(2);
calcu.multiply(5).add(1);

console.log(calcu.num);

If you prefer to interact directly with the interface and plain objects, it is possible but quite cumbersome, as shown below:

const calcu: Calculator = (() =>
{
    let value;

    const fun = function (num: number)
    {
        value = num;

        return fun;
    };
    fun['multiply'] = (num: number) =>
    {
        value *= num;
        return fun;
    };
    fun['add'] = (num: number) =>
    {
        value += num;
        return fun;
    };

    return fun;
})();

calcu(2).multiply(5).add(1);

(It may also be beneficial to define a function that reveals the internal value, as it is currently concealed.)

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 is TS's method of interpreting the intersection between types that have the same named function properties but different signatures (resulting in an error when done

When working with types in Typescript, I encountered an interesting scenario. Suppose we have a type A with two properties that are functions. Now, if we define a type B as the intersection of type A with another type that has the same function properties ...

Here's how you can retrieve URL parameters in NextJs, such as `userid/:this_is_a_param`

I'm struggling to retrieve URL parameters using Next.js. I normally do this with Express by getting a :param from the URL like this: users/:userid/ console.log(req.params.userid) All I've been able to do is get the "userid" from the URL like thi ...

Error encountered when utilizing a mixin in TypeScript due to a parameter issue

Recently, I delved into learning Typescript and decided to experiment with the mixin concept. The code snippet below may seem trivial, but it's all part of the learning process. Surprisingly, everything runs smoothly except for line 42, myInput.sendKe ...

Troubleshooting an Integration Problem Between Express and socket.io

Having trouble reaching the io.on('connect') callback in my basic express setup. The connection seems to stall. Node 12.14.1 express 4.17.1 socket.io 3.0.1 code import express, { ErrorRequestHandler } from 'express'; import path from ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

``There seems to be an issue with the navigationOptions in react-navigation and typescript not

I've been working on converting react-native code from JavaScript to TypeScript and upgrading the version. However, I'm facing an issue with react-navigationHeaderOptions not functioning as expected. I'm unable to pinpoint the cause of this ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

Utilize checkboxes for executing send operations and implementing prevention measures in Angular 9

I'm currently working with Angular 9 and I am facing an issue with a form that includes a checkbox. The form is designed in a way that when the user clicks the save button, it should fill in the name field. However, I have noticed that when the checkb ...

What is the best way to pass down SectionList prop types in TypeScript when using React?

I am working on creating a wrapper for SectionList in React Native that needs to accept all the standard props of SectionList along with some custom ones. How can I set up typescript to accommodate this? Here is what I have tried: import React from &apos ...

Step-by-step guide on implementing a draggable component for selecting the year using React

I am looking to develop a draggable component in React without relying on any third-party library. Below, I have provided an image depicting how the component might look. Currently, my component code appears as follows: import React from 'react'; ...

Retrieving values from objects using Typescript

I am facing an issue while trying to retrieve a value from an object. The key I need to use belongs to another object. Screenshot 1 Screenshot 2 However, when working with Typescript, I encounter the following error message. Error in Visual Studio Is ...

Guide on incorporating Kendo UI typings into a TypeScript module

Currently, I am working with Kendo UI for React and TypeScript. My goal is to import the Kendo UI typings for TypeScript using a "typeof import". Following the guidance provided at https://docs.telerik.com/kendo-ui/third-party/typescript, I successfully i ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

How can TypeScript limit the number of properties allowed to be passed as a function parameter?

Here is what I currently have: export interface RegionNode { nodeSelected: boolean; nodeEditable: boolean; zone: Partial<Zone>; parent: RegionNode | null; children: RegionNode[]; } Now, I am looking for a sleek solution to create ...

Updating a one-to-one relationship in TypeORM with Node.js and TypeScript can be achieved by following these steps

I am working with two entities, one is called Filter and the other is Dataset. They have a one-to-one relationship. I need help in updating the Filter entity based on Dataset using Repository with promises. The code is written in a file named node.ts. Th ...

Implement TypeScript to include type annotations on functions' parameters using destructuring and the rest syntax

Issues with Typing in Typescript Trying to learn typing in Typescript has presented some difficulties for me: I am struggling to convert this code into a strongly-typed format using Typescript. const omit = (prop: P, { [prop]: _, ...rest}) => rest; ...

Encountering a problem with Webpack SASS build where all files compile successfully, only to be followed by a JavaScript

Being a newcomer to webpack, I am currently using it to package an Angular 2 web application. However, I am encountering errors related to SASS compilation and the ExtractTextPlugin while working on my project. Here is a snippet from my webpack configurat ...

Facing numerous "error TS1005" messages when performing a gulp build due to node_modules/@types/ [prop types] and [react] index.d.ts with SPFx Webpart

I am currently in the process of developing a custom spfx webpart that includes a feature to display link previews. In order to achieve this functionality, I integrated this specific library. However, I encountered some challenges during the implementation ...

Discovering if objects possess intersecting branches and devising a useful error notification

I have 2 items that must not share any common features: const translated = { a: { b: { c: "Hello", d: "World" } } }; const toTranslate = { a: { b: { d: "Everybody" } } }; The code ab ...