TypeScript Example: Default Function Parameters

Last updated on August 15, 2021 A Goodman Loading... Post a comment

The code snippet below shows you how to use default function parameters in TypeScript:

const myFunction = (a: string, b: string = 'Default B', c: string = 'Default C') => {
  console.log('A:', a);
  console.log('B:', b);
  console.log('C:', c);
}

// Call the function with just one parameter 
console.log('One parameter provided');
myFunction('Meat');

// Call the function with 2 parameters
console.log('Two parameters provided');
myFunction('Chicken', 'Potato');

// Call the function with 3 parameters
console.log('Three parameters provided');
myFunction('Rice', 'Tomato', 'Salmon');

Output:

One parameter provided
A: Meat
B: Default B
C: Default C

Two parameters provided
A: Chicken
B: Potato
C: Default C

Three parameters provided
A: Rice
B: Tomato
C: Salmon

Important note: The parameters for which you don’t accept default arguments have to come first (stay on the left side).

Further reading:

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like