Home > OS >  Override the value of default parameter while there are optional parameters
Override the value of default parameter while there are optional parameters

Time:12-02

I have a function which takes four parameters, among which the 1st parameter is required, the 2nd & 3rd are optional, the 4th has a default value:

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

In my caller, I would like to provide the value of 1st parameter and override the 4th boolean. How to do that? I can't do MyClass.myFunc("foo", false). Should I re-design the function signature? What is the convention in TypeScript to have a function like that?

CodePudding user response:

  1. You should redefine the order and the usage of the parameters in your function.

  2. Use param?:type

This way you can overload the function call without explicitly sending unnecessary undefined as arguments.

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")

In your case:

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

CodePudding user response:

Here are a couple of ways to achieve the API you asked about:

TS Playground link

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

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

// if you can't modify the class, you can create a function with the 
// parameters ordered by your preference, which calls the original method
// in the function body and returns its return value
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 are all equivalent
MyClass.myFunc('foo', undefined, undefined, false);
MyClass.myRefactoredFunc('foo', false);
myFunc('foo', false);
  • Related