简体   繁体   中英

How can I set a default value for an optional parameter of a function in typescript?

My function in typescript has an optional boolean parameter b.

function foo(a: number, b?: boolean){

   ...

}

How can I define a default value for the parameter b?

You can set the default value in the function definition like that:

function foo(a: number, b: boolean = true) {

    ...

}

Like that the parameter is still optional. But it has a default value in case no value is passed.

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