'Why are the args for my storybook component showing as optional instead of required?

I have a simple loader component

import React from "react";
import { Backdrop, CircularProgress } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

export interface LoaderProps {
  open: boolean;
}

const useStyles = makeStyles((theme) => ({
  backdrop: {
    zIndex: theme.zIndex.drawer + 1,
    color: "#fff",
  },
}));

const Loader: React.FC<LoaderProps> = ({ open }) => {
  const classes = useStyles();

  return (
    <Backdrop className={classes.backdrop} open={open}>
      <CircularProgress color="inherit" />
    </Backdrop>
  );
};

export default Loader;

Here is the story for it:

import React from "react";
import Loader, { LoaderProps } from "./Loader";
import { Story } from "@storybook/react/types-6-0";

export default {
  title: "Loader",
  component: Loader,
  excludeStories: /.*Data$/,
};

export const loader: Story<LoaderProps> = (args) => <Loader {...args} />;
loader.args = {
  open: true,
};

When I hover over open in the args it says the type could be boolean | undefined instead of just boolean? Why is this when the LoaderProps should enforce that is of type boolean?



Solution 1:[1]

Checking the Story type, it's defined as BaseStory<Args, StoryFnReactReturnType> & Annotations<Args, StoryFnReactReturnType>.

BaseStory isn't particularly interesting or relevant here, but Annotations has the property: args?: Partial<Args>.

In your code, Args is LoaderProps, so the Annotations object has an optional property args that itself is all of the LoaderProps properties made optional. That is, loader.args is of type Partial<LoaderProps> which is { open?: boolean }. The fact that it is optional is what allows it to also be undefined.

As for why storybook does this, I can only guess since the documentation in the types on Annotation.args in the type definitions has a dead link. If the properties on args were required, then you would have to set all of the properties in your Props definitions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Explosion Pills