8

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.

4 Answers 4

6

Maybe this is what you are trying to achieve.

function renderComponent(openDialog? : { openDialog?: boolean }) {
    render(
        <Component />
    );

    if (openDialog) clickButton('Import Existing');
}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

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();

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.