DEV Community

Cover image for How to use named arguments in TypeScript functions?
Pierre-Henry Soria ✨
Pierre-Henry Soria ✨

Posted on • Edited on

How to use named arguments in TypeScript functions?

If you are familiar with the keyword / named arguments in programming languages such as Python, Ruby and PHP 8, you probably wonder if the same can be achieved in TypeScript.

This is an excellent question. We are aware that named parameters / named arguments drastically help the readability of the code. With keyword arguments, we can directly tell what the mentioned argument does in the function call.

Use the object destructuring on the function parameters.

Like this 👇

function invertSentence({
  sentence,
  doesFormat
}: {
  sentence: string;
  doesFormat: boolean;
}): string {
  if (doesFormat) {
    return sentence;
  }

  // logic ...

  // split into two segments
  const [stringOne, stringTwo] = sentence.split(
    ". "
  );

  // rebuild the sentence
  const rebuiltString = `${stringTwo} ${stringOne}`;

  return rebuiltString;
}
Enter fullscreen mode Exit fullscreen mode

And then, you will be able to mention the required properties which will be the "named arguments".

invertSentence({ 
  sentence: 'TS makes my job easier. Writing clean code avoids me a headache',
  doesFormat: false
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, TypeScript doesn't offer named arguments natively like what PHP 8 does for instance.
However, thanks to the power of TS's types, we can the types to force our functions' parameters to receive the arguments with their mentioned property names for improving the readability of our code.

Top comments (3)

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Let me know your thoughts and other interesting use-cases you might like to share? 😊

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
pierre profile image
Pierre-Henry Soria ✨ • Edited

Hi Salmin! Sure, what don't you understand? Is is from the TS types?

If this is simpler for you, keep in mind that I could also have stored:

{
    sentence: string;
    doesFormat: boolean;
  }
Enter fullscreen mode Exit fullscreen mode

into an interface like:

interface InvertSentence {
    sentence: string;
    doesFormat: boolean;
  }
Enter fullscreen mode Exit fullscreen mode

and then, the function's signature would become

function invertSentence({
    sentence,
    doesFormat
  }: InvertSentence) {
Enter fullscreen mode Exit fullscreen mode

Good luck!