DEV Community

Discussion on: Write cleaner function's optional parameters

Collapse
 
thealiilman profile image
Ali Ilman • Edited

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?

myFunction("Call me maybe", 12345, { param4: 67890 }) { 
  const { param3, param4 } = optionals;

  // Write any code here
};

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 or undefined for cases where one of the optional parameters isn't needed.

Collapse
 
moseskarunia profile image
Moses Karunia

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. :)

Collapse
 
vinceramces profile image
Vince Ramces Oliveros • Edited

Maybe a typo.

function myFunction("Call me maybe", 12345, optionals = {param4:12356} /** Object */) { 
  const { param3, param4 } = optionals; //Destructuring
  //if you console param3, it will show undefined.

  // Write any code here
};

myFunction("Called", 4123, {param4: 67890});

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.

Collapse
 
moseskarunia profile image
Moses Karunia

Good point! I can see that it can improve readability. Thanks for sharing!