
In TypeScript, a function can have optional and default parameters. In order to make a parameter optional, we can postfix it with a question mark (?). We can provide a default value to a parameter by using the assignment operator (=).
Example:
const example = (name: string, age?: number, job = 'software developer'): void => {
console.log(`Hello ${name}`);
if(age){
console.log(`You are ${age} years old`)
}
console.log(`Your job is ${job}`);
}
example('Batman', 45, 'superhero');
example('Goodman', 39);
Output:
Hello Batman
You are 45 years old
Your job is superhero
Hello Goodman
You are 39 years old
Your job is software developer
Further reading:
- React + TypeScript: Handling Select onChange Event
- Express + TypeScript: Extending Request and Response objects
- Calculate Variance and Standard Deviation in Javascript
- Javascript: Capitalize the First Letter of Each Word (Title Case)
- React + TypeScript: Working with Props and Types of Props
You can also check out our TypeScript category page for the latest tutorials and examples.