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!
Top comments (4)
I'm a newbie when it comes to TypeScript. It's next in my learning backlog. 🤓
By the way, in the function below, where does
optionals
come from?Thanks for sharing by the way! 🙂 Using an object for optional parameters really helps with keeping function calls clean. It burns my eyes seeing
nil
orundefined
for cases where one of the optional parameters isn't needed.Maybe a typo.
however. For readability, it's better to have a named parameters than to have none. by simply wrapping your parameters as object and destructuring it in a function. It's a good practice to have a named parameters when you don't know what parameters have been provided in a function.
JavaScript Named Parameters
Dale L. Jefferson ・ May 30 ・ 1 min read
Good point! I can see that it can improve readability. Thanks for sharing!
Woot! Seems like I was making a typo! The post has been updated. Thanks for pointing it out! Please check it out again. It should makes sense now. :)