Skip to main content

Command Palette

Search for a command to run...

How to use named arguments in TypeScript?

Updated
โ€ข2 min read
How to use named arguments in TypeScript?
P

I'm Pierre-Henry Soria. A passionate full stack engineer, building things that matter, making a real impact on the world.

Really like to take care of others and manage my workflow based on productivity methodologies.

Open to fast-paced changes with rapidly evolving business and technologies. I'm always thirsty to learn and undertake new exciting things and thrilling challenges.

If you are familiar with the keyword / namedarguments 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 using named parameters / named arguments definitely 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 [string1, string2] = sentence.split(
    ". "
  );

  // rebuild the sentence
  const rebuiltString = `${string2} ${string1}`;

  return rebuiltString;
}

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
});

Lastly...

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

{
    sentence: string;
    doesFormat: boolean;
  }

into an interface like:

interface InvertSentence {
    sentence: string;
    doesFormat: boolean;
  }

and then, the function's signature would become

function invertSentence({
    sentence,
    doesFormat
  }: InvertSentence) {

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 codebase โšก๏ธ

More from this blog

Super Passionate Software Engineer

37 posts

Pierre-Henry Soria. A super passionate & enthusiastic software engineer! ๐Ÿš€ True cheese & chocolate lover! ๐Ÿ˜‹ ๐Ÿ‘‰ Reach me at https://ph7.me ๐Ÿ’ซ