Write cleaner function's optional parameters

moseskarunia

Moses Karunia

Posted on October 29, 2019

Write cleaner function's optional parameters

Clean all the codes!


Update:

  1. Code typo fixed.
  2. Adding default value to optional to make it easier to destructure.

Normally, we can put the optionals last in our function declaration. This way we can simply omit it from our calls when we don't need it.

// Declaration
const myFunction = (param1: string, param2: number, param3?: string, param4?: number) { }

// Call
myFunction("Call me maybe", 12345);

Enter fullscreen mode Exit fullscreen mode

But, there's a time where we need to assign param4 without param3.

myFunction("Call me maybe", 12345, undefined, 67890);
Enter fullscreen mode Exit fullscreen mode

I think that's messy, because we are forced to write undefined first. This is getting incrementally annoying if there're more than 1 undefined in-between. (especially if you are a bit OCD like me)

So, I then remember how the flutter team handles optional parameters, and I think it makes my typescript code much cleaner.

// Declaration
const myFunction = (param1: string, param2: number, 
  optionals: { param3?: string, param4?: number } = { }) { }

// Call 1
myFunction("Call me maybe", 12345, { param4: 67890 });

// Call 2
myFunction("Call me maybe", 12345);
Enter fullscreen mode Exit fullscreen mode

And to make things better, we can destructure our optionals first, instead of prefixing everything with optionals..

const myFunction = (param1: string, param2: number, 
  optionals: { param3?: string, param4?: number } = { }) { 
  const { param3, param4 } = optionals;

  // Write any code here
};
Enter fullscreen mode Exit fullscreen mode

UPDATE: I changed the optionals declaration from optionals?: {} to optionals: {} = {}. This way, you can safely destructure optionals even if it's undefined, because it will be replaced with empty object. Please note that the destructured values can still be undefined.

I think this will look cleaner no matter how many optional parameters we have. We can even still omit the optionals completely like before.

myFunction("Call me maybe", 12345);
Enter fullscreen mode Exit fullscreen mode

Win-win for me!


So, what do you think? Maybe you have a better way to write optionals? Let us know!

💖 💪 🙅 🚩
moseskarunia
Moses Karunia

Posted on October 29, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related