How to set a default value to function parameters in TypeScript

3 Answers

0 votes
function sum(x: number = 3, y: number = 8): number {
    return x + y;
}
 
console.log(sum(4, 13)); // 4 + 13
console.log(sum(5)); // 5 + 8
console.log(sum()); // 3 + 8
 
 
       
/*
run:
       
17 
13 
11 
       
*/
   

 



answered Jan 26, 2022 by avibootz
edited Nov 24, 2025 by avibootz
0 votes
const calculateArea = (length: number, width: number = 10): number => {
  return length * width;
};

console.log(calculateArea(5)); // 5 * 10
console.log(calculateArea(5, 20)); // 5 * 10
 
   
   
/*
run:
   
50
100
   
*/

 



answered Jan 26, 2022 by avibootz
edited Nov 24, 2025 by avibootz
0 votes
const func = (id: number = 657321, name: string = 'R2D2'): void => {
    console.log(`${id} : ${name}`);
};

func();
func(9999);
func(8888, 'Harry');
func(undefined); 

 
 
       
/*
run:
       
"657321 : R2D2" 
"9999 : R2D2" 
"8888 : Harry" 
"657321 : R2D2" 

*/
   

 



answered Nov 24, 2025 by avibootz

Related questions

...