TypeScript Example: Default Function Parameters
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:
- React + TypeScript: Using Inline Styles Correctly
- React + TypeScript: Handling Select onChange Event
- React & TypeScript: Using useRef hook example
- React + TypeScript: Handling input onChange event
You can also check out our TypeScript category page for more tutorials and examples.
Subscribe
0 Comments