Reputation: 1937
I am creating a simple function with an object parameter. It accepts openDialog
boolean property which decides whether to run another function. I am not defining an interface for it because it is ever going to be a single property. My issue is how do I define it in such a way that I am no longer required to pass an empty object to that function? openDialog
is optional so what is the right syntax for making that object optional too?
function renderComponent({ openDialog }: { openDialog?: boolean }) {
render(
<Component />
);
if (openDialog) clickButton('Import Existing');
}
Typescript complains about renderComponent()
with
Expected 1 arguments, but got 0.
It accepts renderComponent({})
I am aware of a default parameter function renderComponent({ openDialog }: { openDialog?: boolean } = {}) {
but I am wondering whether there is a different way.
Upvotes: 7
Views: 5946
Reputation: 1544
Since destructuring a possibly undefined object does not work:
function renderComponent(args?: { openDialog?: boolean }) {
// not possible, since type of args is { openDialog?: boolean } | undefined
const { openDialog } = args;
}
I ended up using a default initialization args = {}
:
function renderComponent(args: { openDialog?: boolean } = {}) {
// destructuring works now, since type of args is { openDialog?: boolean } | {}
const { openDialog } = args;
// you can use openDialog now, which ofc may be undefined if not provided
}
// can be called even without passing an empty object
renderComponent();
Notice, that you don't need the ?
after args
if you provide a default value.
Upvotes: 3
Reputation:
Insert ={}
after { openDialog }: { openDialog?: boolean }
but inside the parameter parentheses.
Completely, it looks like this:
function renderComponent({ openDialog }: { openDialog?: boolean } = {} ) {
render(
<Component />
);
if (openDialog) clickButton('Import Existing');
}
Upvotes: 1
Reputation: 112
Maybe this is what you are trying to achieve.
function renderComponent(openDialog? : { openDialog?: boolean }) {
render(
<Component />
);
if (openDialog) clickButton('Import Existing');
}
Upvotes: 6
Reputation: 13
That error:
Expected 1 arguments, but got 0.
means that you must pass (one) object as an argument to this function.
If you would't pass openDialog
parameter with this code you should
call this function like this:
renderComponent({});
If you would have optional argument you should do like this:
function renderComponent(args? : { openDialog?: boolean }) {
// your code
}
renderComponent();
Upvotes: 1