'Typescript passing optional param to function
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 1:[1]
Similar to the previous answer, but you have to handle undefined props:
async function myFunc(prop?: {id?: string}){
const filters = prop && Object.keys(prop).length? { movie_id: prop.id }: {};
// there is use for filters later
}
myFunc(); //works
myFunc({}); //works
myFunc({id: 'abc'}); //works
Solution 2:[2]
interface ImyFunProps = {
id?:number
}
const myFunc = async (prop?: ImyFunProps) => {
const {id} = props;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Riddhi Busa |
