Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Optional Parameter and Rest Parameter together in Typescript?

Tags:

typescript

I want to have a function definition which should contain both Optional and Rest Parameter. While invoking the function, am not getting desired output from the function. While invoking a function should I use some special keyword or something?

In the below function, the address is an optional parameter and names is a Rest Parameter. How can I invoke this function?

function Greet(age:number,address?:string,...names: string[]):void{
    console.log(age);
    console.log(address);
    console.log(names)
}

Greet(20,"Mathan","Maddy")

Here am passing parameters only to age and names. but the second value "Mathan" is getting considered for address in my function.

like image 414
Mathan Avatar asked Sep 01 '25 22:09

Mathan


1 Answers

I don't really see any way you could do it other than explicitly specify undefined for the optional value:

Greet(20, undefined, 'Maddy')

There isn't a way to infer whether the second parameter is the optional one, or the start of the rest ones.

like image 156
Evan Trimboli Avatar answered Sep 03 '25 18:09

Evan Trimboli