Alex Ironside
Alex Ironside

Reputation: 5039

How to create an optional interface?

I have this case:

interface IRenderComponent {
  urlToHideAt?: string;
  links?: IInternalNavbarLink[];
  currentLink?: IInternalNavbarLink;
}
const renderComponent = ({ urlToHideAt, links, currentLink }: IRenderComponent) => {

And it kind of makes sense. I am setting all children as optional, but in doing this, I get an error each time I try to use the function,

Expected 1 arguments, but got 0.ts(2554)

Which makes sense. I set the props as optional, not the one param.

My question, then, is how to set the whole argument { urlToHideAt, links, currentLink } as optional. How do I achieve that?

Upvotes: 1

Views: 90

Answers (2)

Raphaël
Raphaël

Reputation: 3726

You cannot make the interface optional but you can give a default value to the first argument of ˋrenderComponentˋ to make it optional:

const renderComponent = ({ urlToHideAt, links, currentLink }: IRenderComponent = {}) => {
    // Do something
}

Upvotes: 0

D. Pardal
D. Pardal

Reputation: 6587

You can use default parameters:

const renderComponent = ({ urlToHideAt, links, currentLink }: IRenderComponent = {}) => {}

If the caller doesn't pass the first parameter, it will default to {}, which is a valid IRenderComponent, and urlToHideAt, links, currentLink will all be undefined. ({}.links === undefined)

Upvotes: 2

Related Questions