i have a function with following shape
const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code }
i need to make second parameter (object) optional, is it possible ?
You can assign an empty object {}
as default param value to it. Wrapping object param type with Partial
to make its memebers optional, same as adding question mark { objArg?: string }
const func = (arg1: string, { objArg = true }: Partial<{ objArg: string | boolean }> = {}) => {
console.log(objArg)
}
You can set an default value and it will be automatically optional:
const func = (
arg1: string,
{ objArg = true }: { objArg: boolean } = undefined
) => {}
If you want to make an parameter optional, you should use ?(question mark) before :
and optional parameter has to be the last parameter of function. For more information check this page. https://www.typescripttutorial.net/typescript-tutorial/typescript-optional-parameters/
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.