Write cleaner function's optional parameters
Moses Karunia
Posted on October 29, 2019
Clean all the codes!
Update:
- Code typo fixed.
- 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);
But, there's a time where we need to assign param4
without param3
.
myFunction("Call me maybe", 12345, undefined, 67890);
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);
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
};
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);
Win-win for me!
So, what do you think? Maybe you have a better way to write optionals? Let us know!
Posted on October 29, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.