Home > Enterprise >  how to make optional object parameter in Typescirpt?
how to make optional object parameter in Typescirpt?

Time:06-08

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 ?

CodePudding user response:

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)
}

CodePudding user response:

You can set an default value and it will be automatically optional:

const func = (
  arg1: string,
  { objArg = true }: { objArg: boolean } = undefined
) => {}

CodePudding user response:

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/

  • Related