简体   繁体   中英

Optional object parameter in typescript

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.

Maybe this is what you are trying to achieve.

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

    if (openDialog) clickButton('Import Existing');
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM