Dotfiles for macOS

Loading...

Leveraging the power of TypeScript to improve DX and reduce bugs in React with conditional props.

Either or conditional prop

check npm package

next image component - link to src

<Button text="Click me!" />
<Button>
    <span>Click me! <img src=".." /></span>
</Button>

By adding prop?: never, we let TypeScript know that this prop is not allowed.

type ImageSize =
  | { width?: never; height?: never; layout: "fill" }
  | { width: number; height: number; layout?: "responsive" | "fixed" };

This roughly translates to: if we omit the height and width, the layout has to be "fill". If we decide to pass a fixed height and width, we can omit the layout prop or pass "responsive" or "fixed". This API might seem familiar to you, as it is exactly what Next does in it's Image component: src

Conditional prop, only allow if another prop is passed

I like to think of this _ as if this, then that_

Let's continue on with our button example: We want to add the option to render our button as an anchor, but keep the button styling and props.

// Renders a button node
<Button>Foo</Button>

// Renders an anchor as the root node
<Button as="a" href="/faq">Go to FAQs</Button>