Conditional props generator 🔮
Why?
- Reduce bugs 🐛
- Better DX 👾
- Write better components 🥳
- Save time 😃
Usage
The type will be exported to /generated
.
To use the type, simply extend it using the &
key at the end of your prop type:
import { MyConditionalType } from "generated/types.ts";
type ExampleProps = {
color: string;
height: number;
} & MyConditionalType;
Of course you can just cut + paste the type
to your actual type as well, if you don't want
to hide the abstraction of it.
Examples and explanations
This section contains some explanations and examples
of when and why you would want to use the different conditionals.
One-of-type / either or type
This type is used when only one of the sets of types should
be passed
Example with only 1 type in each set:
Inspiration from Next.js Image
component:
We have created an Image
component that
We have created our own Button
component.
We have 2 different possible props: text
or children
.
If text is passed, we will render the text internally.
If children is passed, the developer might wrap the text in some other tags with classes. However, it doesn't make sense to pass both these props:
<Button text="Click me!" />
<Button>Click me!</Button>
This type will be generated:
type EitherTextOrChildrenType =
| { text: string; children?: never }
| { text?: never; children: React.ReactNode };
Simply extend our props with our new type:
type ButtonProps = {
size: "small" | "big";
} & EitherTextOrChildrenType;
You can include an infinite amount of typesets,
and how many types you want in each typeset.
The example shows 2 typesets each containing 1 type
just for simple demonstration.
Conditional prop, only allow if another prop is passed
Used when a prop only can be passed when in combination
with another specific prop. Let's continue on
with our Button component.
Often you want a button to just be and behave as an
anchor tag, but look like your standard button.
A great way to solve this with our Button component
is to choose what root DOM node should be rendered.
We create 2 new props: as
and href
.
IMAGE: blurLoad=true blurLoadSrc={src}
NEW
Let's say we have a comment component, that displays a comment written by an user.
Sometimes, this comment might be quite long, so we should let the user collaps/truncate it
in order to not take up too much space. This is where you could use a conditional type; a type
that is dependent on another type.
In the CLI, first write the type that decides if the other type should be allowed,
press enter and then type the props that are dependent on this type.
Example:
collapsable:true
Allow these props:
defaultCollapsed:boolean
<Comment collapsable defaultCollapsed={false} />
<Comment />
<Comment defaultCollapsed>
<Button text="Show me more" as="Link" href="https://..." />
A good example of this is Next.js Image
component. You can