Ask Question

How can I enforce, that a TypeScript Type require at least of one two properties?

I have a custom React Component which should either receive a href or an onClick event handler, depending if it should act as a link or a call-to-action button. One of those properties should definitely be set, so I want to enforce this via TypeScript. What would be the best solution for this?

TypeScriptReact

39 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

A possible solution for this is to have a Base-Interface of your Props and then two other Interfaces which extend the Base-Interface and act as the different implementations of your Component props. So you can force that you component is either a Link or a Button Component.

See this code snippet:

interface IBaseProps {
  name: string;
}

interface ILinkProps extends IBaseProps {
  href: string;
}

interface IButtonProps extends IBaseProps {
  onClick: () => void;
}

Then in your component you allow the props to be one of the implementation types. In your code logic you only need to find out if your component now got passed the Link or Button implementation of the props. TypeScript guards come in pretty handy for this.

function isLink(props: ILinkProps | IButtonProps): props is ILinkProps {
  return (props as ILinkProps).href !== undefined;
}

const Component = (props: ILinkProps | IButtonProps) => {
  const { name } = props;

  if (isLink(props)) {
    // now TypeScript knows that the props is of type ILinkProps
  } else {
    // here it knows that the props is of type IButtonProps
  }
};
export default Component;
๐ŸŽ‰
1
โค๏ธ
1
Last edited on