[SOLVED] Typescript passing optional param to function

Issue

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?

Solution

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 } = {}) => { ... }

Answered By – TheTisiboth

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.