简体   繁体   中英

How to use Optional Parameter and Rest Parameter together in 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM