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;
}
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
});
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)
Let me know your thoughts and other interesting use-cases you might like to share? 😊
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:
into an interface like:
and then, the function's signature would become
Good luck!