How to use named arguments in TypeScript?

How to use named arguments in TypeScript?

ยท

2 min read

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

ย