Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters.

function bar() {

    let p = 0;

    function f() {
    }

    f.prop = function(d) {
        return !arguments.length ? p : (p = d, f);
    }

    return f;

}

With this approach, I can easily create and set values like const b = bar().prop(2), where b represents the function and allows for additional chained statements. To retrieve the property, I simply use b.prop(), which cannot be further chained.

As I attempt to convert this functionality into TypeScript, I came across a solution that provides proper typing but appears somewhat convoluted.

p.prop = (...args: [number?]) => !args.length ? p : (p = args[0]!, f);

This complexity is heightened when the argument can take multiple types.

p.prop = (...args: [(number | boolean)?]) => !args.length ? p : (p = args[0]!, f);

Are there any conventional TypeScript methods to achieve this setting and retrieving behavior?

Answer №1

When working with the prop function, keep in mind that it only accepts a single argument. To simplify and align the Typescript version with Javascript, consider declaring d as optional and then performing a check for its existence instead of using rest syntax or an array:

f.prop = function(d?: number) {
    return d === undefined ? p : (p = d, f);
}

If you need to handle additional types, just specify the type in the d parameter while also defining the type for p, since it will be assigned there:

function bar() {
    let p: number | boolean = 0;
    function f() {
    }
    f.prop = function (d?: number | boolean) {
        return d === undefined ? p : (p = d, f);
    }
    return f;
}
const b = bar().prop(2)

Answer №2

To define a function interface, you can do so by using the following syntax:

interface Chainable {
    (): void;
    prop: (data: any) => Chainable
};

function baz(): Chainable {
   ... 
   const chain = f;
   return chain;

}

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

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

Enhance your iPhone web app with high-resolution retina images!

As I develop a mobile web application accessible on any smartphone, I have the index.html file available for review: The app includes 2 jQuery functions. One detects if the user is using an iPhone and displays a bubble with instructions to add it to the h ...

Dynamic translation routing with Next.js

My goal is to create dynamic translation routes for specific pages in next js using i18next. While the following code works well, it currently routes to all pages and generates errors during next build. const router = useRouter(); const path = router.route ...

The div block containing the table is experiencing horizontal overlap as additional elements are inserted

When creating a table within the div section of the code, I am incorporating text using the DRAG and DROP feature with appropriate styling. The table adjusts in size when I resize my window, indicating that it is functioning correctly. However, as the num ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

In MongoDB and Node.js, encountered error: 'Unable to access property 'collection' as it is undefined'

I'm encountering a type error with my collection function that was previously functioning without any issues. This code was working perfectly in another project of mine. After reusing a lot of the code, I started experiencing this error. My MongoDB c ...

Unable to assign a local variable in Jquery .ajax() function to a global variable

Check out this example of a jQuery AJAX code: $(document).ready(function() { var custom_array = new Array(); $.ajax({ url: 'data.json', type: 'get', dataType: 'json', success: function(response) { $ ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

conditional operator that compares values in router events

As I examine an object, links = { link1: 'page1', link2: 'page2', link3: 'page3', link4: 'page4', link5: 'page5', link6: 'page6' } I possess a function for retrieving t ...

Node.js Friendship NetworkIncorporating Friendships in Node

Currently, I have successfully set up a real-time chat application using node.js and socket.io. My next goal is to allow users to create accounts, search for other users by username, and send friend requests to start chatting. I have tried searching onlin ...

Library of User Interface components for React Native applications

As I embark on my journey of building my first major app using React Native, a question comes to mind. Is there a UI framework available for React Native that offers pre-styled components right out of the box? Similar to how Ionic provides a base theme a ...

What is the proper way to implement jest.mock in a describe or it block?

Using typescript and jest, I am faced with a scenario involving two files: users.service.ts, which imports producer.ts. In an attempt to mock a function in producer.ts, I successfully implement it. import { sendUserData } from "./users.service"; const pro ...

"Disabling Dropzone.js functionality once a file has been selected - here's how

When using my dropzone, I typically choose a file to save first and then click the save button. However, I am facing an issue: how can I disable the dropzone area after selecting a file? I attempted the following approach: accept: function (file, done) { ...

Best method for simultaneously calling multiple routes in Node.js and Express

What is the best approach for handling multiple routes simultaneously in Node.js and Express? For instance, if I have two routes defined as app.get('/', routes.views.index); and app.all('/header', routes.views.header); I want both route ...

Angular rest call is returning an undefined response object attribute

When attempting to retrieve the attribute of a response object, it is returning as "undefined". var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope, $http) { $scope.addNewChoice = functio ...

Is there a way to identify if a user clicks on the scrollbar within my div element?

Is there a way to detect when someone mouses down on the scrollbar of a div element with scrollbars? ...

Finding the Attachment ID on a JIRA Issue Page with JavaScript

Currently, I am using an ajax call that requires the attachment id in its URL. The URL is hardcoded as follows: url: AJS.contextPath()+"/rest/api/latest/attachment/10415" jQuery.ajax({ url: AJS.contextPath()+"/rest/api/latest/attachment/10415", TYPE: "GET ...

Iterating variables in Vue.js is reminiscent of the process in AngularJS

When working on my application using vue.js, I am interested in finding the last repeated element within a v-for directive. I understand that in angularjs, there is a similar concept using the $last loop variable in its ngRepeat directive: <div ng-repe ...

Protractor: Command Line Tips for Providing URLs

When running a Protractor test, the URL is usually specified in the spec file. However, it is possible to also include it directly in the spec.js file: browser.get('www.google.com'); To run the test, the command would be: protractor conf.js I ...

Using Vue.js 3 to fetch data from a REST API using the Axios

How do I properly retrieve and display an array using axios.get in Vue? The data is not showing up in my table cells when I use the v-for directive. Could the issue be related to the v-for statement? <tr v-for="params in form" :key=" ...