Change the default parameter value when optional parameters are present

I am working with a function that has four parameters, where the first parameter is mandatory, the second and third are optional, and the fourth has a default value:

class MyClass {
   static myFunc(param1: string, param2? : string, param3? : string, param4:boolean=true) 
   {
      ...
   }
}

When calling this function, I want to provide a value for the first parameter and override the default boolean value of the fourth parameter. However, simply using

MyClass.myFunc("foo", false)
doesn't work. Should I reconsider the design of the function signature? What is the common practice in TypeScript for handling such scenarios?

Answer №1

  1. Redefining the order and usage of parameters in your function is recommended.

  2. Consider using param?:type for overloading the function call efficiently.

This approach helps avoid passing unnecessary undefined arguments explicitly.

const func = (a:number, b:boolean = true, c?:string, d?:string) => {
    console.log(a, b, c, d)
}

func(1)
func(1, false)
func(1, false, "Hello")
func(1, false, "Hello", "World")

For your specific situation:

class MyClass {
   static myFunc(param1:string, param2:boolean = true, param3?:string, param4?:string) 
   {
      ...
   }
}

Answer №2

You can achieve the desired API in a few different ways:

Check out this TypeScript Playground link

class MyClass {
  // The method mentioned in your query
  static myFunc (
    param1: string,
    param2?: string,
    param3?: string,
    param4 = true,
  ): void {
    console.log([param1, param2, param3, param4]);
  }

  // Refactored version with reordered parameters
  static myRefactoredFunc (
    param1: string,
    param4 = true,
    param2?: string,
    param3?: string,
  ): void {
    console.log([param1, param2, param3, param4]);
  }
}

// If you can't modify the original class, create a function with custom parameter order 
// that calls the original method internally and returns its result
const myFunc = (
  param1: Parameters<typeof MyClass['myFunc']>[0],
  param4?: Parameters<typeof MyClass['myFunc']>[3],
  param2?: Parameters<typeof MyClass['myFunc']>[1],
  param3?: Parameters<typeof MyClass['myFunc']>[2],
): ReturnType<typeof MyClass['myFunc']> => MyClass.myFunc(param1, param2, param3, param4);

// These three approaches are functionally identical
MyClass.myFunc('foo', undefined, undefined, false);
MyClass.myRefactoredFunc('foo', false);
myFunc('foo', false);

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

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Show a Pop-Up When a Key is Pressed

My website popup features a 'Close' button in the top right corner, a text section with a background image, and a 'Print' button at the bottom. The popup automatically appears when the page loads. However, once closed, there is currentl ...

Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code: $('.delblk').click(function(e) { e.preventDefault(); var id = $(this).attr('id').substr(7); ...

Typescript Error: TS2339: Unrecognized property 'map' on datatype 'string'

It appears that typescript does not currently support the new object types in ECMAScript 2015 (6th Edition, ECMA-262). Here is the code snippet I am working with: const SkipAny: string = requestBody.SkipAny; CurTester.SkipAny = SkipAny.map((value) => { ...

Guide to scraping a website using node.js, ASP, and AJAX

I am currently facing an issue where I need to perform web scraping on this specific webpage form. This webpage is dedicated to vehicle technical reviews, and you can try inputting the car license CDSR70 for testing purposes. As mentioned earlier, I am u ...

What could be causing my component to not properly redirect to the Movies Page?

Currently, I am utilizing React-Router v6.4 along with Vite for setting up a React project. I am facing an issue where the routes are not redirecting to the movies component as expected. App.jsx import "./App.css"; import { createBrowserRouter, ...

What is the best way to locate every object based on its ID?

Currently, I am facing an issue where I have a list of IDs and I need to search for the corresponding object in the database. My tech stack includes Nodejs, Typescript, TypeORM, and Postgres as the database. The IDs that I am working with are UUIDs. ...

Dynamic Bootstrap tooltip

I have a simple Javascript code snippet that I'm struggling with: $("#myinput").hover(function(){ if(condition){ $(this).tooltip({placement: "bottom", title: "mytitle"}); } ); Accompanied by its HTML cou ...

When using React Leaflet, the initial object is found to be undefined in a useState scenario while trying to draw

Attempting to iterate through an object that has been obtained from a CSV file containing Locations and corresponding Lat/Lng pairs. However, the initial loop iteration results in all values of the object being undefined. The code snippet I am using is: i ...

What is the best way to adjust the color of a button element?

I've been troubleshooting the mouseover function of my JavaScript button object. The goal is to have a function call (specifically show()) within the object that detects the mouseover event and changes the button's color to grey. I suspect that t ...

A guide on switching out an HTML element with an AJAX response

How can I dynamically replace an HTML element with Ajax response? I know how to remove the element, but I'm unsure how to then insert the new content from the Ajax call. For instance, let's say I have the following code: <ul id="products"> ...

What could be the reason for the incorrect usage of the "this" value in the jQuery hover event listener when using bind(this)?

Here is an example to consider: function dropDownToggle() { console.log($(this)[0].id); } $("a").hover( dropDownToggle.bind(this) ); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a id= ...

Reference loss occurs in Angular Ionic when using @ViewChild

This situation is straightforward I am dealing with a reference in this format @ViewChild('myElement') myElementVar : SomeClass; The element I am referencing appears like this <element #myElement *ngIf="someBoolean"></element> As ...

Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details). https://i.stack.imgur.com/T2DQe.png [{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":&qu ...

I am currently working on determining whether a given string is a palindrome or not

I'm currently working on a function that checks whether a given string is a palindrome. So far, my tests are passing except for the following cases: (_eye, almostomla, My age is 0, 0 si ega ym.) This is the function I've implemented: function pa ...

Playing audio induces slight delay

Issue: I created a game similar to Flappy Bird using Three.js. Every time I tap the screen, a flapping sound is triggered. However, playing this audio causes a slight lag in the game, making it less smooth. The lag only occurs when the audio is played and ...

Using string interpolation within the onclick event (Ionic 2 + Angular 2)

One question that's troubling me - I'm attempting to pass a string within an "onclick" event in my Ionic 2 app, but it keeps throwing an error. <button onclick="window.plugins.socialsharing.shareViaWhatsApp(null, null, '{{sound.file}}&a ...

Utilizing ES6 modules in an Adobe XD extension: A comprehensive guide

Is it possible to utilize ES6 imports within XD plugins? When attempting to use import Vue from 'vue', the build task is successful, but XD throws an error in the developer console during plugin loading: Plugin Error: Error loading plugin <s ...

Understanding the process of configuring Quasar Language in SSR Mode using route parameters

Is there a way to incorporate Quasar Language Packs while utilizing this specific routing method and SSR mode? const routes = [ { path: '/:locale?', beforeEnter: localeNavGuard, children: [ ... ] } ] ...

Error: The default export is not a component compatible with React in the specified page: "/"

I'm facing an issue while building my next app. Despite using export default, I keep encountering an error that others have mentioned as well. My aim is to create a wrapper for my pages in order to incorporate elements like navigation and footer. vi ...