TypeScript: Function with Optional and Default Parameters

Updated: November 17, 2021 By: A Goodman Post a comment

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:

You can also check out our TypeScript category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles