Home > Software design >  Typescript passing optional param to function
Typescript passing optional param to function

Time:01-18

I have a request function that can accept a param for filtering, or not (it is optional). I can pass something to my func like this

myFunc({id: 123})

and then inside my func I have this constructor:


const myFunc = async ({ id }: { id?: string }) => {
  const filters = {
    ...(id && { movie_id: id })
  };
  // there is use for filters later
}

as you can see the id is optional but I can't send empty param fields.

such as:

myFunc(); //doesn't work
myFunc({}); //works

is there a way to make this work for when I call myFunc() without anything inside the brackets and still have an optional param?

CodePudding user response:

You could type your param:

type MyFuncProps = {
  id?:number
}

const myFunc = async (prop?: MyFuncProps) => { ... }

This way, the argument is optional

Or, if you don't want to type your parameters, you can use a default value like this:

const myFunc = async ({ id }: { id?: string } = {}) => { ... }

CodePudding user response:

interface ImyFunProps = {
  id?:number
}

const myFunc = async (prop?: ImyFunProps) => { 
  const {id} = props;
}

CodePudding user response:

Similar to the previous answer, but it you have to handle undefined props:

interface ImyFunProps {
  id?:string
}

const myFunc = async (prop?: ImyFunProps) => { 

  if(prop){
  const {id} = prop;
    const filters = {
    ...(id && { movie_id: id })
  };
  console.log(filters)
  // there is use for filters later
  }
}

myFunc(); //doesn't work
myFunc({}); //works
myFunc({id: 'abc'}); //works
  •  Tags:  
  • Related